Mysql 中 not in 的查询优化

本文为博主原创,转载请注明出处:

   最近做性能优化时,通过开启 MySQL 的慢日志查询配置,发现 有一条慢sql,在这里记录下分析和优化的过程。

   该慢 sql 如下:

select id from fucdn_customer_domain where id not in (
    select customer_domain_id from fucdn_customer_domain_cache where cache_time > 0
) and status = 1

  通过 explain 或 desc 查看该sql 的执行计划:

           

 

   可以看出这条sql 的执行计划分为两步。第一步先执行  fucdn_customer_domain_cache  这张表的子查询,这张表查询结束后再进行外层的查询,且访问类型均为 ALL,所以导致该sql 执行耗时较长。

  使用 left join 进行关联优化,将sql 中的子查询,优化为左连接,即减少 sql 执行嵌套的层数,优化后的sql 如下:

select id from fucdn_customer_domain fcd LEFT JOIN (
    select customer_domain_id from fucdn_customer_domain_cache where cache_time > 0
) t on fcd.id = t.customer_domain_id where fcd.status = 1 and t.customer_domain_id is null

   查看优化后的sql 执行计划:

                  

   优化后 id 都变为了1,且过滤的数量比not in 时少了很多。由于本地数据库数据量比较少, 优化后效果并不明显,当拿到 压测环境或现网环境时,性能提高了至少一半以上。

 

posted @ 2022-03-07 23:41  香吧香  阅读(4941)  评论(0编辑  收藏  举报