SQL語句常用最佳化技巧(一),sql語句最佳化技巧

來源:互聯網
上載者:User

SQL語句常用最佳化技巧(一),sql語句最佳化技巧
要提高SQL語句的執行效率,最常見的方法就是建立索引,以及盡量避免全表掃描。給大家整理一些常見的SQL最佳化技巧,避免全表掃描。一個簡單的最佳化,也許能讓你的SQL執行效率提高几倍,甚至幾十倍。
 
1、避免在where子句中使用 is null 或 is not null 對欄位進行判斷。

 如:

select id from table where name is null

在這個查詢中,就算我們為 name 欄位設定了索引,查詢分析器也不會使用,因此查詢效率底下。為了避免這樣的查詢,在資料庫設計的時候,盡量將可能會出現 null 值的欄位設定預設值,這裡如果我們將 name 欄位的預設值設定為0,那麼我們就可以這樣查詢:

 select id from table where name = 0

2、避免在 where 子句中使用 != 或 <> 操作符。

 如:

 select name from table where id <> 0

資料庫在查詢時,對 != 或 <> 操作符不會使用索引,而對於 < 、 <= 、 = 、 > 、 >= 、 BETWEEN AND,資料庫才會使用索引。因此對於上面的查詢,正確寫法應該是:

 select name from table where id < 0 union all select name from table where id > 0

這裡我們為什麼沒有使用 or 來連結 where 後的兩個條件呢?這就是我們下面要說的第3個最佳化技巧。

 
3、避免在 where 子句中使用 or來連結條件。
 
如:
 select id from table where name = 'C++' or name = 'C#'

這種情況,我們可以這樣寫:
 select id from table where name = 'C++' union all select id from table where name = 'C#'

4、少用 in 或 not  in
 
雖然對於 in 的條件會使用索引,不會全表掃描,但是在某些特定的情況,使用其他方法也許效果更好。如:
 select name from table where id in(1,2,3,4,5)

像這種連續的數值,我們可以使用 BETWEEN AND,如:
 select name from table where id between 1 and 5

5、注意 like 中萬用字元的使用。
 
下面的語句會導致全表掃描,盡量少用。如:
 
select id from table where name like '%jayzai%'

或者
 select id from table where name like '%jayzai'

而下面的語句執行效率要快的多,因為它使用了索引:
 select id from table where name like 'jayzai%'

6、避免在 where 子句中對欄位進行運算式操作。
 
如:
 select name from table where id/2 = 100

正確的寫法應該是:
 select name from table where id = 100*2

7、避免在 where 子句中對欄位進行函數操作。
 如:
 select id from table where substring(name,1,8) = 'jayzai'

 select id from table where datediff(day,datefield,'2014-07-17') >= 0


這兩條語句中都對欄位進行了函數處理,這樣就是的查詢分析器放棄了索引的使用。正確的寫法是這樣的:

 select id from table where name like 'jayzai%'

select id from table where datefield <= '2014-07-17'

也就是說,不要在 where 子句中的 = 左邊進行函數、算術運算或其他運算式運算。

 

8、在子查詢中,用 exists 代替 in 是一個好的選擇。
 
如:
 select name from table where id in (select id from b) 


如果我們將這條語句換成下面的寫法:

select name from table a where exists (select 1 from b where id = a.id)


這樣,查詢出來的結果一樣,但是下面這條語句查詢的速度要快的多。 

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.