新人一枚,求大神分析下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

解决方案 »

  1.   

    內表大的时候用exist,是因为只用遍历外表的数据
    但是in是在内存中查询,所以exist跟in的时间差不多也是可能发生的。
      

  2.   

    针对(3)select id from employee,单独执行的话,需要4秒左右,但是全查询的话(3)只要0.001秒。
    这点不明白SQL执行的逻辑,希望大神解释下 @二楼
      

  3.   

    explain打印看看
      

  4.   

    5.7 不记得是那个版本开始, in 有时候会被自动优化为 exists 执行,所以验证一下执行计划吧
      

  5.   

    试试这个
    SELECT
      t1.*
    FROM
      employee t1
      JOIN employee_department t2
        ON t2.employee_id = t1.id;