发布于 1年前

MySQL使用NOT IN存在null值导致结果错误的解决方法

house表:

create table house (address varchar(200) not null, heating varchar(50));

表中有两个字段,address地址,不能为null,凉爽程度heating 可以为null。

插入记录:

insert into house values ('A', null),('B','hot');

in查询语句:

select address from house where heating in ('cool');

结果为空,因为不存在heating为cool的房子。

not in查询语句:

select address from house where heating not in('cool');

我们可能预期应该输出A和B,实际结果输出为B。

在MySql中,NOT IN是使用列表中的值做相等比较, “!=”不相等时返回true。如果值为null,!=null始终为false。

NOT(TRUE) 为FALSE, NOT(FALSE) 为TRUE, 而NOT(UNKNOWN) 还是UNKNOWN。null表示UNKNOW

解决方法:

对in返回true取反,非true则是想要的结果

select address from house where heating in ('cool') is not TRUE;
©2020 edoou.com   京ICP备16001874号-3