这 :
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:
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
什么都不会退回