我有三个看起来像这样的表:
表joins
|ID|JOIN_NAME|
1 persons
2 companies
表information
|ID|JOIN_ID|
1 1
2 2
表information_extra_persons
|ID|INFORMATION_ID|NAME|
1 1 John
表information_extra_companies
|ID|INFORMATION_ID|NAME|
1 2 IBM
如何在一个SQL中将这些表连接在一起?我尝试过类似的东西:
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`
但我无法让它发挥作用。当然这不是我的实际表设置,但它是相同的原则。有谁知道如何在一个SQL中获取所有信息?
答案 0 :(得分:3)
实际上这是四张桌子,而不是三张桌子。这不仅仅是一个挑剔 - 看起来问题的实质是“如何使用表格的名称作为加入标准的一部分?” (即,如何将information_extra_表视为单个表?)
答案是:你不能。 (在动态SQL之外。)
在这个特定的案例中,以下内容应该返回我认为您正在寻找的内容:
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
或者,效率较低(但更通用)的方法可能是:
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