1、现象

1.1、使用not int 子查询

select
	* 
from
	`users` 
where
	id not in ( select uid from role_user )

查询结果为:

1.2、结果对吗?

当然不对

1.2.1、查询一下role_user的uid结果

select uid from role_user

查询结果为:

1.2.2、查询一下users表的数据

select * from `users` 

1.2.3、分析查询结果

role_user表的数据uid只有一个1和null,所以说应该能查询到users表的id=2的数据

实际执行的sql为:

select
	* 
from
	`users` 
where
	id not in ( 1,null )

但是查询的结果依然为:

如果我把sql改一下:

select
	* 
from
	`users` 
where
	id not in ( 1)

所以可以看到是由于not in 中的结果有null 导致无法查询出数据的

2、为什么会产生这样的结果?

2.1、null属于什么?

2.2、not in 的底层实现

select
	* 
from
	`users` 
where
	id not in ( 1,null )

not in 多个值的实现原理为

select
	* 
from
	`users` 
where
	id != 1
	and id != null

第一反应是不是觉得是符合的啊?users表的id是主键,所以说都不为空值啊

但是为什么会这样?

我们来执行一个sql

select 1 !=null

可以看到查询结果为null,所以说上面的sql里面的id!=null的结果也是null

由于null无法参与boolean运算,默认为false,所以说上面的条件中and后面的id!=null永远是false

3、结论

说明not in中如果值有null,那么将查询不到数据