当前位置:网站首页>Mysql的in和exists用法区别
Mysql的in和exists用法区别
2022-08-03 07:40:00 【棒棒吃不胖】
一.构建模拟环境
表A有某学校所有学生的姓名
表B有某学校所有的班级
要求通过班级查询所有学生的姓名
二.比较
1)首先用in
查询姓名
select * from A where name in (select name from B);
该命令等价于
先走子查询 select name from B;
再走A表 select * from A where A.name=B.name;
它相当于一个大循环,嵌套着里面的一个小循环
其中子查询为外部循环,主查询语句是内部的循环
可以看出:
内表的结果无论如何都需要遍历(外层循环),这是不可避免的。
所以子查询A小于B,使用in
性能越好。
2)用exists
查询姓名
select * from A where exists ( select 1 from B where A.name=B.name );
该命令等价于:
先走表A select * from A;
再走表B select * from B where A.name=B.name;
它也是一个大循环嵌套一个内循环
不过,此处表A查询是外循环
可以看出:
外层表(A)的结果无论如何都需要遍历(外层循环),这是不可避免的。
所以A数据量大于B,使用exists
性能越好。
三.结论
当A是外层循环(必须遍历),B是内层循环
A数据量小于B数据量,用in
A数据量大于B数据量,用exists
(此时B是外层循环)
一句话:选择外层循环表数据量小的。
边栏推荐
- [Kaggle combat] Prediction of the number of survivors of the Titanic (from zero to submission to Kaggle to model saving and restoration)
- 剑指offer专项突击版第18天
- thop 使用心得
- AI mid-stage sequence labeling task: three data set construction process records
- 【OpenCV】 - 显示图像API之imshow()对不同位深度(数据类型)的图像的处理方法
- 力扣(LeetCode)214. 打家劫舍 II(2022.08.02)
- 差分(前缀和的逆运算)
- Dapr 与 NestJs ,实战编写一个 Pub & Sub 装饰器
- DeFi明斯基时刻:压力测试与启示
- How does Mysql query two data tables for the same fields in two tables at the same time
猜你喜欢
随机推荐
WordPress主题-B2美化通用子主题商业运营版
postman将接口返回结果生成csv文件到本地
2022年 SQL 优化大全总结详解
ArcEngine (1) Loading vector data
AI中台序列标注任务:三个数据集构造过程记录
用diskpart的offline命令弹出顽固硬盘
千万级别的表分页查询非常慢,怎么办?
The use of the database table structure document generation tool screw
LeetCode 264:丑数
Roson的Qt之旅#105 QML Image引用大尺寸图片
Oracle Rac Cluster File Directory Migration
工控机防勒索病毒浅析
酷雷曼上新6大功能,全景营销持续加码
pyspark @udf loop using variable problem
STL迭代器
ArcEngine (six) use the tool tool to realize the zoom in, zoom out and translation of the pull box
day12---接口和协议
Fortify白盒神器20.1.1下载及安装(非百度网盘)
JS作用对象API技巧
【图像边缘检测】基于matlab灰度图像的积累加权边缘检测【含Matlab源码 2010期】