加入两个表并显示它来自哪里

时间:2017-01-23 15:07:14

标签: mysql sql join

我有两张桌子:

ID, actor, description....
FK_ID, other_description...

我现在将加入这两个表,以便得到以下结果:

ID|actor|description|other_description
1, Bud Spencer, >MainDescription<, null
1, Bud Spencer, null, Other_Description1
1, Bud Spencer, null, Other_Description2
.....

如何撰写查询?

谢谢。

3 个答案:

答案 0 :(得分:1)

如果您需要同一行中的值您可以在id和fk_id

上使用左连接
select a.ID, a.actor, a.description, b.other_description
from table1 as a
left join table2 as b on a.ID = b.FK_ID

如果您需要同一列中的不同值,则可以使用union

select ID, actor, description
from table1 
union
select fk_ID, null, other_description
from table2

如果您需要所有值,可以使用union all

答案 1 :(得分:0)

SELECT A.ID A.actor A.description B.other_description
FROM tableA A
INNER JOIN tableB B ON
A.ID = B.FK_ID

答案 2 :(得分:0)

SELECT a.ID, a.actor, a.description, b.other_description
FROM DB1 a
JOIN DB2 b 
on a.ID=b.FK_ID