本文主要介绍SQL查询的性能优化及其替代方案。
1.避免in,disdinct,用exists代替。用NOT EXISTS替代NOT IN
例如: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
解决办法:数据库不要留NULL,可设置默认0等。 select id from t where num = 0 。或者用where>=0这样
4.避免在 where 子句中使用 != 或 <> 操作符
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
参考:
https://www.cnblogs.com/yunfeifei/p/3850440.html
https://www.cnblogs.com/exe19/p/5786806.html
sql优化经典例子