新人一枚,求大神分析下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中有没有类似@@ROWCOUNT的系统变量(存储过程)
- 一张表中两个字段需同时要默认获取当时时间,如何创建触发器
- 数据库结合webservice
- MySQL数据显示不全的问题
- mysql4.0.25升级成4.1.22,数据插入的问题.
- linux下启动mysql的问题!急,求助大虾!!!!!
- mysql能调用java/c程序吗(linux系统)
- 跪求:如何在已经建立的数据库中建立数据表?????
- 如果发现自己的mysql没有充分利用CPU该关注那些参数?
- mysql表修复
- redis/memcahed 不具备查询功能为何作可为数据库的缓存?
- [Mysql]新手求助:设置密码出现1064错误
但是in是在内存中查询,所以exist跟in的时间差不多也是可能发生的。
这点不明白SQL执行的逻辑,希望大神解释下 @二楼
SELECT
t1.*
FROM
employee t1
JOIN employee_department t2
ON t2.employee_id = t1.id;