我在 SQL Server 中有兩個表:
Table1: Table2:
Col1(PK): Col2: Col1:
------------------------ ------
1 1 1
2 <null> 2
3 5 10
4 <null> 11
5 12 12
現在我想加入這些表,Col2但結果我希望所有行的Col2值為空,如果不是空,則只有Col2存在于Table2.
當我嘗試Left Join在結果中使用時,有行來自Col1(PK) = 3但Col2 = 5不存在于Table2.
我怎樣才能實作它?
我試過這樣的東西,但它只回傳匹配的行并忽略空行
select *
from Table1 t1
join Table2 t2 on t1.Col2 = t2.Col1 or t1.Col2 is null and t2.Col1 is null
結果 Col1(PK) 1、2、4、5 中的預期行。因為 T1.Col2 中的 null 是可以的,并且在 T1.Col2 中的第 1(1) 和 5(12) 行中的值存在于 T2.Col1
If T1.Col2 == null => Is Ok Can Return If T1.Col2 != null => Check If Exists Value in T2.Col1 => Exists Is ok 可以回傳,不存在 跳過
uj5u.com熱心網友回復:
我會使用NOT NULL和EXISTS你的描述中提到的
select *
from table1 t1
where col2 is null or exists (
select 1
from table2 t2
where t1.col2 = t2.col1
)
uj5u.com熱心網友回復:
內部聯接將僅回傳匹配的記錄,并且在聯接條件中將簡單地忽略空值。Null 不能與 null 進行比較,因為沒有值。
假設您在 table2 中有 col2,您可以嘗試使用左連接。
select *
from Table1 t1
full outer join Table2 t2 on t1.Col2 = t2.Col2
where t2.col2 is not null or t1.col2 is null;
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/418726.html
標籤:
