数据库教程:mysql中not in隐含陷阱详解

1、现象1.1、使用not int 子查询select* from`users` whereid not in ( select uid from role_user )查询结果为:1.2、结果对吗?

1、现象

1.1、使用not int 子查询

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

查询结果为:

mysql中not in隐含陷阱详解

1.2、结果对吗?

当然不对

1.2.1、查询一下role_user的uid结果

select uid from role_user

查询结果为:

mysql中not in隐含陷阱详解

1.2.2、查询一下users表的数据

select * from `users` 

mysql中not in隐含陷阱详解

1.2.3、分析查询结果

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

实际执行的sql为:

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

但是查询的结果依然为:

mysql中not in隐含陷阱详解

如果我把sql改一下:

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

mysql中not in隐含陷阱详解

所以可以看到是由于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  

mysql中not in隐含陷阱详解

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

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

3、结论

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

需要了解更多数据库技术:mysql中not in隐含陷阱详解,都可以关注数据库技术分享栏目—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/dtteaching/1076935.html

(0)
上一篇 2022年4月12日
下一篇 2022年4月12日

精彩推荐