本文主要介绍SQL查询的性能优化及其替代方案。html
1.避免in,disdinct,用exists代替。用NOT EXISTS替代NOT INsql
例如:select num from a where num in(select num from b) 代替成:数据库
select num from a where exists(select 1 from b where num=a.num) 性能优化
(低效): SELECT DISTINCT DEPT_NO,DEPT_NAME FROM DEPT D , EMP E WHERE D.DEPT_NO = E.DEPT_NO函数
(高效): SELECT DEPT_NO,DEPT_NAME FROM DEPT D WHERE EXISTS ( SELECT ‘X' FROM EMP E WHERE E.DEPT_NO = D.DEPT_NO);性能
2.尽可能避免全表扫描,首先应考虑在 where 及 order by 涉及的列上创建索引优化
3.尽可能避免在 where 子句中对字段进行 null 值判断 select id from t where num is null spa
解决办法:数据库不要留NULL,可设置默认0等。 select id from t where num = 0 。或者用where>=0这样.net
4.避免在 where 子句中使用 != 或 <> 操做符code
5.避免在 where 子句中使用 or 来链接条件,若是一个字段有索引,一个字段没有索引,将致使引擎放弃使用索引而进行全表扫描
(低效)select id from t where num=10 or Name = 'admin'
(高效)select id from t where num = 10
union all
select id from t where Name = 'admin'
6.避免in,若为连续数值,尽可能用between
(低效)select id from t where num in(1,2,3)
(高效)select id from t where num between 1 and 3
7.避免在 where 子句中对字段进行表达式操做
(低效)select id from t where num/2 = 100
(高效)select id from t where num = 100*2
8.避免在where子句中对字段进行函数操做
(低效)select id from t where substring(name,1,3) = ’abc’ -–name以abc开头的id
select id from t where datediff(day,createdate,’2005-11-30′) = 0 -–‘2005-11-30’ --生成的id
(高效)select id from t where name like 'abc%'
select id from t where createdate >= '2005-11-30' and createdate < '2005-12-1'
9.优化GROUP BY
提升GROUP BY 语句的效率,能够经过将不须要的记录在GROUP BY 以前过滤掉。下面两个查询返回相同结果但第二个明显就快了许多。
(低效) SELECT JOB , AVG(SAL) FROM EMP GROUP BY JOB HAVING JOB = ‘PRESIDENT' OR JOB = ‘MANAGER'
(高效 )SELECT JOB , AVG(SAL) FROM EMP WHERE JOB = ‘PRESIDENT' OR JOB = ‘MANAGER' GROUP BY JOB
参考:
http://www.javashuo.com/article/p-fxaxlhna-y.html