网站首页 > 文章精选 正文
前言:近期在处理业务实际问题时发现使用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。
猜你喜欢
- 2025-07-10 失业程序员复习python笔记——mysql
- 2025-07-10 MySQL高性能注意事项简述(高性能mysql重点章节)
- 2025-07-10 MySQL触发器介绍(mysql触发器使用)
- 2025-07-10 2021年超详细的java学习路线总结—纯干货分享
- 2025-07-10 MySQL常见错误及解决方法(mysql常见错误提示及解决方法)
- 2025-07-10 MySQL索引失效场景分析与优化(mysql索引何时失效)
- 2025-07-10 MySQL实战:聊聊子查询 vs 联表查询应该如何选择?
- 2025-07-10 SQL 神操作:用 LEFT JOIN 干掉 NOT IN,查询速度直接飙车!
- 2025-07-10 The entangled power of BRICS(the power of dreams)
- 2025-07-10 谁再在 SQL 中写 in 和 not in,直接走人!
- 最近发表
-
- Vue3+Django4全新技术实战全栈项目|高清完结
- 工厂模式+策略模式消除 if else 实战
- 每天一个 Python 库:httpx异步请求,让接口测试飞起来
- 如何高效实现API接口的自动化测试?
- 前端工程化:从“手忙脚乱”到“从容协作”的进化记
- 使用C#创建服务端Web API(c#开发web服务器)
- SpringBoot之旅第四篇-web开发(springboot做web项目)
- 一文读懂SpringMVC(一文读懂新型政策性金融工具)
- Rust Web编程:第十二章 在 Rocket 中重新创建我们的应用程序
- Apache Druid 数据摄取——本地数据和kafka流式数据 一篇文章看懂
- 标签列表
-
- newcoder (56)
- 字符串的长度是指 (45)
- drawcontours()参数说明 (60)
- unsignedshortint (59)
- postman并发请求 (47)
- python列表删除 (50)
- 左程云什么水平 (56)
- 计算机网络的拓扑结构是指() (45)
- 编程题 (64)
- postgresql默认端口 (66)
- 数据库的概念模型独立于 (48)
- 产生系统死锁的原因可能是由于 (51)
- 数据库中只存放视图的 (62)
- 在vi中退出不保存的命令是 (53)
- 哪个命令可以将普通用户转换成超级用户 (49)
- noscript标签的作用 (48)
- 联合利华网申 (49)
- swagger和postman (46)
- 结构化程序设计主要强调 (53)
- 172.1 (57)
- apipostwebsocket (47)
- 唯品会后台 (61)
- 简历助手 (56)
- offshow (61)
- mysql数据库面试题 (57)