MySQL null字段 与 not in

工作中遇到此问题:

查询 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值