数据库查询优化之子查询优化

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代替。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对来客网的支持。如果你想了解更多相关内容请查看下面相关链接