新人一枚,求大神分析下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
-- 外表大的情况
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
解决方案 »
- 怎么备份mysql数据库中一张表
- 应不应该增加新表储存新字段?
- 一个SQL语句
- linux下mysql问题,我照着网上的帖子做了,但还是没有解决。
- mysql在查询过程中能否省略掉statistics的步骤?
- MySQL query browser如何向表插入数据啊?
- [分享]刚学mysql,写了一个反回两日期的相差分钟数的函数
- 求一 查询语句(请前辈指教)在线等
- 已经有一个表tablename,可是现在我发现我还需要一栏string,又不想改动其中的数据,我该怎么作
- Grant创建的用户名无法登录数据库
- redis/memcahed 不具备查询功能为何作可为数据库的缓存?
- [Mysql]新手求助:设置密码出现1064错误
但是in是在内存中查询,所以exist跟in的时间差不多也是可能发生的。
这点不明白SQL执行的逻辑,希望大神解释下 @二楼
SELECT
t1.*
FROM
employee t1
JOIN employee_department t2
ON t2.employee_id = t1.id;