我试图从具有两列sample
和col1
的表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
值的行?
答案 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.)。