SQL NOT IN NULL的問題
在sql查詢中,有時候會遇到如下情況:兩個表table1(10萬條唯一的記錄,table2(1萬條唯一的記錄)都只有一個欄位:col001 在執行:select count(*) from table1 where col001 not in (select col001 from table2)時,如果table2中有null的話,這句話就有可能執行的結果為0,但是如果把table2中的null刪掉的話就又正常了。
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
SQL-92標準要求對空值的等於(=)或不等於(<>)比較取值為FALSE。當SET ANSI_NULLS為ON時,即使 column_name中存在空值,使用WHERE column_name = NULL的SELECT語句仍返回零行;即使column_name中存在非空值,使用WHERE column_name <> NULL的SELECT語句仍返回零行。
當SET ANSI_NULLS為OFF時,等於(=)和不等於(<>)比較運算子不遵從SQL-92標準。使用WHERE column_name = NULL的SELECT語句返回column_name中含有空值的行。使用WHERE column_name <> NULL的SELECT語句返回列中含有非空值的行。此外,使用WHERE column_name <> XYZ_value的SELECT語句返回所有非XYZ值和非NULL的行。
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------select * from table1 t where not exists(select 1 from table2 where ID=t.ID)--用exists
select count(*) from table1 where col001 is not null and col001 not in (select col001 from table2)
子查詢必須排除NULL值.例如:
select count(*) from table1 where col001 not in(select col001 from table2 WHERE col001 IS NOT NULL)