我嘗試執行以下查詢,但沒有得到任何數據,儘管它應該得到一個行:爲什麼[NOT IN]語法不起作用?
select * from [DB1.table1] where col1 not in (select col2 from DB2.table2)
COL1,COL2 VARCHAR類型
爲什麼它不工作?
我嘗試執行以下查詢,但沒有得到任何數據,儘管它應該得到一個行:爲什麼[NOT IN]語法不起作用?
select * from [DB1.table1] where col1 not in (select col2 from DB2.table2)
COL1,COL2 VARCHAR類型
爲什麼它不工作?
「不起作用」對您的問題不是很好的描述,但在幾乎所有情況下,這都是由子選擇返回NULL值引起的。
你可能想這樣的:
select * from [DB1.table1]
where col1 not in (select col2 from DB2.table2 where col2 is not null);
與NULL
比較總是產生「不確定」,因此如果至少一個排從子選擇包含在col2
列NULL
整個表達式是「未定義」。由於未定義不是「真」,整個查詢不會返回任何內容。
如果你有NULL
S IN col2
在table2
,你會得到你所描述的行爲:
create table table2 (
col2 varchar(10) null
)
insert into table2 (col2) values ('abc'),(null)
create table table1 (
col1 varchar(10) null
)
insert into table1 (col1) values ('abc'),('def')
select * from table1 where col1 not in (select col2 from table2)
生成任何行。這是因爲NOT IN
的結果變爲UNKNOWN
,一旦發生NULL
比較。如果這是你的situtation正確的邏輯
select * from table1 where col1 not in (select col2 from table2 where col2 is not null)
:
您可以修復它。
正如其他人已經指出,造成這一問題的原因,你可以達到同樣的效果,使用LEFT JOIN
它比謂詞IN
與NULL
vlaues安全:
select t1.*
from [DB1.table1] AS T1
LEFT JOIN DB2.table2 AS t2 ON t1.col1 = t2.col2
where t1.col2 IS NULL;
COL1的類型= COL2?整理? – 2013-03-28 07:41:54
如果'col2'可爲空且其中一行爲* * * NULL,它將不返回行 - 但您沒有給我們足夠的信息以知道這是否是這種情況。 – 2013-03-28 07:42:25