本文為博主原創,轉載請注明出處:
最近做性能優化時,通過開啟 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 時少了很多。由於本地數據庫數據量比較少, 優化后效果並不明顯,當拿到 壓測環境或現網環境時,性能提高了至少一半以上。
