为什么数据库的左外连接查询特别慢?

就查了7条记录就要2秒钟,绝对不能忍,用内连接很快,为什么用左外连接就慢成蜗牛。

查询语句:

explain select * from (
    select * from device where enterprise_id in (
        select enterprise_id from user_enterprise where user_id = 1
    )
) t1
left join (
    select * from device_data
    where device_data_id in ('139212', '139295', '142934', '142935')
) t2
using(device_id)

表结构:

表结构

explain结果:

图片说明

1.本身所有外链接执行成本就高于内连接
2.where in中使用子查询这种写法是极其不推荐的,in语法是有限制的。通常使用关联的方式写
3.执行计划中已经指明了存在表扫描

select * from 
(select distinct enterprise_id from user_enterprise) a
inner join
device b on a.enterprise_id = b.enterprise_id
left join
device_data c on b.device_id = c.device_id
where c.device_data_id in ('139212', '139295', '142934', '142935')

个表的数据量影响很大,一般来说是小表作为主表来关联。