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代替。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對VeVb武林網的支持。
新聞熱點
疑難解答