資料庫查詢優化之子查詢優化
阿新 • • 發佈:2020-01-09
1. 案例
取所有不為掌門人的員工,按年齡分組!
select age as '年齡',count(*) as '人數' from t_emp where id not in (select ceo from t_dept where ceo is not null) group by age;
如何優化?
①解決dept表的全表掃描,建立ceo欄位的索引:
此時,再次查詢:
②進一步優化,替換not in。
上述SQL可以替換為:
select age as '年齡',count(*) as '人數' from emp e left join dept d on e.id=d.ceo where d.id is null group by age;
結論: 在範圍判斷時,儘量不要使用not in和not exists,使用 left join on xxx is null代替。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對我們的支援。如果你想了解更多相關內容請檢視下面相關連結