NOT IN过滤掉NULL值

时间:2020-06-24 07:05:29

标签: sql-server null notin

我试图从具有两列samplecol1的表col2中过滤掉一些预定义的值。

我的查询:

select *
from sample
where (col1 is not null or col2 is not null)
and col1 not in (1,2)
and col2 not in (3,4);

但是,以上查询过滤掉了所有空值(在col1或col2中)。

示例:下面的行被过滤掉了,

col1 col2
---------
7 null
null 8

将查询修改为以下内容时,我得到了预期的结果。

select *
from sample
where (col1 is not null or col2 is not null)
and (col1 not in (1,2) or col1 is null)
and (col2 not in (3,4) or col2 is null);

即使在NOT IN中未指定NULL,为什么NULL仍过滤出具有NOT IN值的行?

2 个答案:

答案 0 :(得分:1)

什么都不等于NULL,什么都不等于NULL。对于NULL NOT IN (1,2)之类的表达式,其结果为 unknown (重要)为 not true;表示未满足WHERE。这就是为什么在您的第二个查询中处理NULL的原因。

或者,您可以使用EXISTS。它可能不是直观的,但可以处理NULL值:

WITH VTE AS(
    SELECT *
    FROM (VALUES(1,3),(2,4),(3,5),(7,NULL),(NULL,8))V(col1,col2))
SELECT *
FROM VTE
WHERE NOT EXISTS(SELECT 1
                 WHERE Col1 IN (1,2)
                   AND Col2 IN (3,4));

答案 1 :(得分:0)

尝试一下

SET ANSI_NULLS OFF
select *
from sample
where (col1 is not null or col2 is not null)
and col1 not in (1,2)
and col2 not in (3,4);

ANSI NULL开/关: 此选项指定ANSI NULL比较的设置。启用此选项后,任何将值与null进行比较的查询都将返回0。禁用此选项时,将值与null进行比较的任何查询都将返回一个空值(https://blog.sqlauthority.com/2007/03/05/sql-server-quoted_identifier-onoff-and-ansi_null-onoff-explanation/#:~:text=ANSI%20NULL%20ON%2FOFF%3A,null%20returns%20a%20null%20value.)。

https://stackoverflow.com/questions/129077/null-values-inside-not-in-clause#:~:text=NOT%20IN%20returns%200%20records,not%20the%20value%20being%20tested.中讨论的