簡體   English   中英

select table1 中的所有行,以及 table2 中不在表 1 中的行

[英]select all rows from table1, and rows from table2 that are not in table 1

我嘗試了很多解決方案(加入、聯合等),但到目前為止我無法得到想要的結果,現在我只是感到困惑......
我有兩張桌子:

表格1

ID - Name
0 - John
1 - Jack
2 - Anna
3 - Liam
4 - Luke

表2

ID - FullName - City
0 - John Smith - New York
1 - Jack Smith - Houston
2 - Anna Smith - Houston
'' - Owen Smith - Chicago
'' - Rosa Smith - Chicago

有些行可能在表 1 中但不在表 2 中,有些在表 2 中但不在表 1 中。

我需要 select 表 1 的所有行和表 2 中的所有行減去兩個表中與 ID 匹配的行,結果我需要所有需要的列才能知道結果來自哪里。
就像是:

結果:

ID - Name - FullName - City
0 - John - John Smith - '' (name!='' so i know it's from table1)
1 - Jack - Jack Smith - '' (name!='' so i know it's from table1)
2 - Anna - Anna Smith - '' (name!='' so i know it's from table1)
3 - Liam - '' - '' (name!='' so i know it's from table1)
4 - Luke - '' - '' (name!='' so i know it's from table1)
'' - '' - Owen Smith - Dallas (name='', city!='' so i know it's from table2)
'' - '' - Rosa Smith - Las Vegas (name='', city!='' so i know it's from 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM