工作中遇到此问题:
查询 select * from 表A where 字段A not in(select 字段b from 表B)
若 字段A 中包含null值,则null值不能被查询出
例:
create table A(
id int(4) NOT NULL,
nam varchar(100) DEFAULT NULL,
num int DEFAULT NULL);
insert into A(id,nam,num)
values(1,'job',2),
(2,'tony',3),
(3,null,4),
(4,'hery',7);
其中 nam 字段包含 null 值
执行下面查询
select * from A where nam not in ('job','tony');
nam 为null字段未被查询出
解决办法:
1、查询时加上查询字段 is null 的语句
select * from A where nam not in ('job','tony') or nam is null;
2、修改字段中null值为空值后再查询
修改:
set sql_safe_updates = 0;
update A set nam = '' where nam is null;
select * from A ;
查询:
select * from A where nam not in ('job','tony');
3、使用 not exists