MySql 优化 in 和 exists

knbsyoo15 2018-06-04 11:09:34
新人一枚,求大神分析下exists 和in。本人自己测试,建了两张表:employee 1000万条数据; employee_department 14条数据。
-- 外表大的情况
explain select t1.* from employee t1
where t1.id in (select employee_id from employee_department);
查询(1)耗时:0.002s
explain select t1.* from employee t1 where exists (
select 1 from employee_department where employee_id = t1.id
);
查询(2)耗时:23s
这个查看执行计划明白。但是内表大的情况,就纠结了:
-- 内表大的情况
select t1.* from employee_department t1 where t1.employee_id in (
select id from employee
)
查询(3):0.001s
select t1.* from employee_department t1 where exists (
select 1 from employee where id = t1.employee_id
)
查询(4):0.001s
和网上主流说法,内表大的情况,使用exists表示看不明白。环境MySql 5.7
...全文
1251 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
AHUA1001 2018-11-28
  • 打赏
  • 举报
回复
试试这个
SELECT
t1.*
FROM
employee t1
JOIN employee_department t2
ON t2.employee_id = t1.id;

Rotel-刘志东 2018-11-09
  • 打赏
  • 举报
回复
就看一下执行计划
zjcxc 2018-06-06
  • 打赏
  • 举报
回复
5.7 不记得是那个版本开始, in 有时候会被自动优化为 exists 执行,所以验证一下执行计划吧
oyljerry 2018-06-05
  • 打赏
  • 举报
回复
explain打印看看
knbsyoo15 2018-06-05
  • 打赏
  • 举报
回复
针对(3)select id from employee,单独执行的话,需要4秒左右,但是全查询的话(3)只要0.001秒。 这点不明白SQL执行的逻辑,希望大神解释下 @二楼
oyljerry 2018-06-04
  • 打赏
  • 举报
回复
內表大的时候用exist,是因为只用遍历外表的数据 但是in是在内存中查询,所以exist跟in的时间差不多也是可能发生的。

56,679

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧