SQL優化總結

本文主要介紹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

http://www.javashuo.com/article/p-bgtiyytt-z.html

sql優化經典例子 

相關文章
相關標籤/搜索