mysql - 选择 table1 中的所有行,以及 table2 中不在表 1 中的行
问题描述
我尝试了很多解决方案(连接、联合等),但到目前为止我无法得到想要的结果,现在我很困惑......
我有两个表:
表格1
ID - 姓名
0 - 约翰
1 - 杰克
2 - 安娜
3 - 利亚姆
4 - 卢克
表2
ID - 全名 - 城市
0 - 约翰史密斯 - 纽约
1 - 杰克史密斯 - 休斯顿
2 - 安娜史密斯 - 休斯顿
'' - 欧文史密斯 - 芝加哥
'' - 罗莎史密斯 - 芝加哥
有些行可能在表 1 中但不在表 2 中,有些在表 2 但不在表 1 中。
我需要选择表 1 的所有行和表 2 中的所有行减去两个表中与 ID 匹配的行,并且作为结果,我需要拥有所有需要的列才能知道结果来自哪里。
就像是:
结果:
ID - 姓名 - 全名 - 城市
0 - John - John Smith - '' (name!='' 所以我知道它来自 table1)
1 - Jack - Jack Smith - '' (name!='' 所以我知道它来自 table1 )
2 - Anna - Anna Smith - '' (name!='' 所以我知道它来自 table1)
3 - Liam - '' - '' (name!='' 所以我知道它来自 table1)
4 - Luke -' ' - '' (name!='' 所以我知道它来自 table1)
'' - '' - Owen Smith - Dallas (name='', city!='' 所以我知道它来自 table2)
'' - '' - 罗莎史密斯 - 拉斯维加斯(名称='',城市!='' 所以我知道它来自 table2)
我希望我做的例子足够清楚,谢谢。
解决方案
假设这两个表通过它们相关id
,这应该做你想要的:
select id, name, t2.fullName, t2.city
from table1 t1
left join table2 t2 on t2.id = t1.id
union all
select t2.id, null, t2.fullName, t2.city
from table2 t2
where not exists (select 1 from table1 t1 where t1.id = t2.id)
另一种选择是聚合:
select id, max(name) name, max(fullName) fullName, max(city) city
from (
select id, name, null fullName, null city from table1
union all
select id, null, fullName, city from table2
) t
group by id