这个:
Error not in ('Timeout','Connection Error');
在语义上等价于:
Error <> 'TimeOut' AND Error <> 'Connection Error'
关于空值比较的规则也适用于 IN。所以如果Error的值为NULL,数据库就不能使表达式为真。
要修复,您可以这样做:
COALESCE(Error,'') not in ('Timeout','Connection Error');
或者更好:
Error IS NULL OR Error not in ('Timeout','Connection Error');
或者更好:
CASE WHEN Error IS NULL THEN 1
ELSE Error not in ('Timeout','Connection Error') THEN 1
END = 1
OR 不会短路,CASE 会以某种方式使您的查询短路
也许一个具体的例子可以说明为什么NULL NOT IN expression什么都不返回:
鉴于此数据:http://www.sqlfiddle.com/#!2/0d5da/11
create table tbl
(
msg varchar(100) null,
description varchar(100) not null
);
insert into tbl values
('hi', 'greet'),
(null, 'nothing');
然后你做这个表达:
select 'hulk' as x, msg, description
from tbl where msg not in ('bruce','banner');
那只会输出'hi'。
NOT IN 被翻译为:
select 'hulk' as x, msg, description
from tbl where msg <> 'bruce' and msg <> 'banner';
NULL <> 'bruce'无法确定,甚至不是真的,甚至不是假的
NULL <> 'banner'无法确定,甚至不是真的甚至不是假的
所以空值表达式,有效解析为:
can't be determined AND can't bedetermined
事实上,如果您的 RDBMS 在 SELECT 上支持布尔值(例如 MySQL、Postgresql),您可以看到原因:http://www.sqlfiddle.com/#!2/d41d8/828
select null <> 'Bruce'
返回 null。
这也返回 null:
select null <> 'Bruce' and null <> 'Banner'
假设您使用的是NOT IN,它基本上是一个 AND 表达式。
NULL AND NULL
结果为 NULL。所以就像你在做一个:http://www.sqlfiddle.com/#!2/0d5da/12
select * from tbl where null
不会返回任何东西