sql数据库:简单谈谈有关SQL优化问题
首先声明,此文章所有观点纯属个人经验与看法,如有不妥,还请留言给予指正。

1. 尽量避免使用select * 查询所有,除非你真的需要所有列数据,否则应该只检索需要列的数据
2. 使用exists代替in,以查询木有参加考试的学生信息为例,
使用in:
select * from student s where s.id not in(select c.stuid from chengji c)
使用exists:(高效)
select * from student s where not exists(select c.stuid from chengji c where s.id = c.stuid )
3. 使用exists代替distinct:以员工和部门表为例
使用distinct:
select distinct d.deptName,e.name from department d,employee e where d.id = e.deptid
使用exists:
select d.deptName,e.name from department d where exists
(
select e.id from employee e where e.deptid = d.id
)
4. 表名尽量添加别名,这样可以减少sql重复解析时间
5. 少用having,尽量使用where条件过滤掉不符合要求数据,千万不要分组再来使用having过滤,数据过滤应提前在分组前完成,having只能用于过滤少量数据,能不用就尽量不用。
6. 多表链接时,数据量小的表尽量放在from 关键字的右边。
7. 能过滤掉较多数据的条件应放在where的后边,能过滤掉的越多就越靠后放置。
8. 尽量避免使用where %??%,应该使用where ??%或where %??方式,因为两边都模糊会使该列的索引查询失效。
9. 避免使用not in、is not null,因为会使列索引失效,尽量使用外联结outer join或not exists替代
10. 避免在索引列上使用聚合函数,那样会使索引失效,前提是该列有建立索引,否则不用谈优化。
11. where 条件尽量避免类型隐式转换,因为会使索引失效,
比如:where t.phoneNum = 12345678
应该写成 where t.phoneNum = “12345678”,虽然不加引号也不报错。
12. 尽量使用exists代替子查询
13. 用>=替代>
14. 使用union all替代union,后者在合并两个结果集后还会重新排序,前者直接返回两个结果集并集。
15. 避免使用 | | 进行列合并,而应该使用where....and替代
本文来源 我爱IT技术网 http://www.52ij.com/jishu/110.html 转载请保留链接。
- 评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
-
