0

I have three tables that looks something like this:

Table joins

|ID|JOIN_NAME|
 1  persons
 2  companies

Table information

|ID|JOIN_ID|
 1  1
 2  2

Table information_extra_persons

|ID|INFORMATION_ID|NAME|
 1  1              John

Table information_extra_companies

|ID|INFORMATION_ID|NAME|
 1  2              IBM

How can i join together these tables in one SQL? I've tried something like:

SELECT * FROM `information`
INNER JOIN `information_extra_(SELECT `name` FROM `joins` WHERE `id` = `join_id`)`
ON `information_extra_(SELECT `name` FROM `joins` WHERE `id` = `join_id`)`.`information_id` = `information`.`id`

but I can't get it to work. Of course this isn't my actual table setup, but it's the same principle. Does anyone know how to get all the info in just one SQL?

1
  • 1
    if you need to have the JOIN dynamic this is impossible as SQL doesn't provide anything to do that! Commented Oct 31, 2011 at 9:52

1 Answer 1

3

That's actually four tables, not three. This isn't just a nitpick - it looks as though the substance of your question is "how can I use the name of the table as part of the join criteria?" (ie. how can the information_extra_ tables be treated as a single table?)

To which the answer is: you can't. (Outside of dynamic SQL.)

In this specific case, the following should return what I think you are looking for:

select j.join_name joined_entity,
       case when j.join_name = 'persons' then p.name
            else c.name
       end joined_entity_name
from information i
inner join joins j on i.join_id = j.id
left join information_extra_persons p on i.id = p.information_id
left join information_extra_companies c on i.id = c.information_id

Alternatively, a less efficient (but more general) approach might be:

select j.join_name joined_entity,
       v.name joined_entity_name
from information i
inner join joins j on i.join_id = j.id
inner join (select 'persons' entity, information_id, name from information_extra_persons
            union all
            select 'companies' entity, information_id, name from information_extra_companies) v
           on i.id = v.information_id and j.join_name = v.entity
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.