我有以下表格
表A
ID "Other Columns"
1
2
3
Run Code Online (Sandbox Code Playgroud)
表B
ID "Other Columns"
3
4
5
Run Code Online (Sandbox Code Playgroud)
返回以下结果的有效方法是什么?
结果
ID "Other Columns"
1
2
4
5
Run Code Online (Sandbox Code Playgroud)
完整的外连接应该可以工作,并且只能通过每个表一次。它们可能很棘手,所以请仔细测试!
SELECT
isnull(A.ID, B.ID) ID
,"Other columns" -- Handle nulls properly!
from TableA A
full outer joing TableB B
on B.ID = A.ID
where not (A.ID is not null
and B.ID is not null)
Run Code Online (Sandbox Code Playgroud)
您可以UNION ALL使用 aLEFT JOIN来确定 是否ID不在另一个表中。请记住,两个表之间的列数和数据类型必须匹配:
Select A.Id, A.OtherColumns
From TableA A
Left Join TableB B On A.Id = B.Id
Where B.Id Is Null
Union All
Select B.Id, B.OtherColumns
From TableB B
Left Join TableA A On A.Id = B.Id
Where A.Id Is Null
Run Code Online (Sandbox Code Playgroud)