sql语句中 [not]exists和[not]in的区别
笔记哥 /
04-18 /
5点赞 /
0评论 /
838阅读
**前言**:近期在处理业务实际问题时发现使用in导致查询速度非常慢,于是查阅资料后发现使用exists能极大缩短查询时间,便将此经历记录下来。
# 数据源:
grade表

stu\_info表

# exists与in
## in
`select name from stu_info where stu_no in ( select distinct stu_no from grade);`
执行结果:

执行流程:
- 首先通过子查询查出有成绩的所有学生学号
- 拿到结果后与user表进行比对
in相当于多个or,如果内表即子查询返回m条记录,那么会用外表去遍历匹配内表,查m次。
in是先查内表,在查外表。
## exists
`select name from stu_info where exists (select * from grade where stu_info.stu_no = grade.stu_no);`
执行结果:

执行流程:
- 首先查询外表,及执行 select name from stu\_info
- 然后根据每条记录执行内表,判断内表中where条件是否成立,成立返回true,该行记录保留;不成立返回false,该行记录舍弃,得到最终结果。
exists是先查外表,再查内表,根据外表行数去逐条查询。
## 区别:
内表m条,外表n条
in:循环比对n次
exists:循环比对m次
## 什么时候用in什么时候用exists?
- 当内表大外表小,即m>n时,使用in
- 当内表小外表大,即m<n时,使用exists
- 当内表外表数据量差距很小时,用哪个都可以
# not in 与 not exists:
比对结果与上述相反,但执行流程与上述相同
`select name from stu_info where stu_no not in ( select distinct stu_no from grade);`
`select name from stu_info where not exists (select * from grade where stu_info.stu_no = grade.stu_no);`
结果均为:

# 注:
- exists子句中返回结果只为true或false,因此无论select后面时\*或者某些字段效果都一样,mysql在子查询中忽略这些字段。
如`select name from stu_info where exists (select * from grade where stu_info.stu_no = grade.stu_no);`与`select name from stu_info where exists (select 1 from grade where stu_info.stu_no = grade.stu_no);`执行结果是相同的。
- exists子句中返回任意行即为true,即便是包含null值的行,若不返回任何行则为false。
如:`select name from stu_info where exists (select null);`等同于`select name from stu_info;`,因为select null返回含null的行,exists子句返回true。
`select name from stu_info where exists (select * from grade where stu_no = '100');`等同于`select name from stu_info where false;`,不返回任意行,因为exists子查询中的结果不返回任意行,exists返回false。
- 以上可参考文档:Subqueries with EXISTS or NOT EXISTS
本文来自投稿,不代表本站立场,如若转载,请注明出处:http//www.knowhub.vip/share/2/2358
- 热门的技术博文分享
- 1 . ESP实现Web服务器
- 2 . 从零到一:打造高效的金仓社区 API 集成到 MCP 服务方案
- 3 . 使用C#构建一个同时问多个LLM并总结的小工具
- 4 . .NET 原生驾驭 AI 新基建实战系列Milvus ── 大规模 AI 应用的向量数据库首选
- 5 . 在Avalonia/C#中使用依赖注入过程记录
- 6 . [设计模式/Java] 设计模式之工厂方法模式
- 7 . 5. RabbitMQ 消息队列中 Exchanges(交换机) 的详细说明
- 8 . SQL 中的各种连接 JOIN 的区别总结!
- 9 . JavaScript 中防抖和节流的多种实现方式及应用场景
- 10 . SaltStack 远程命令执行中文乱码问题
- 11 . 推荐10个 DeepSeek 神级提示词,建议搜藏起来使用
- 12 . C#基础:枚举、数组、类型、函数等解析
- 13 . VMware平台的Ubuntu部署完全分布式Hadoop环境
- 14 . C# 多项目打包时如何将项目引用转为包依赖
- 15 . Chrome 135 版本开发者工具(DevTools)更新内容
- 16 . 从零创建npm依赖,只需执行一条命令
- 17 . 关于 Newtonsoft.Json 和 System.Text.Json 混用导致的的序列化不识别的问题
- 18 . 大模型微调实战之训练数据集准备的艺术与科学
- 19 . Windows快速安装MongoDB之Mongo实战
- 20 . 探索 C# 14 新功能:实用特性为编程带来便利