转自http://blog.youkuaiyun.com/startexcel/article/details/5764562
在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)