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 時少了很多。由於本地數據庫數據量比較少, 優化后效果並不明顯,當拿到 壓測環境或現網環境時,性能提高了至少一半以上。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM