要提高SQL語句的執(zhí)行效率,最常見的方法就是建立索引,以及盡量避免全表掃描。在本章MySQL教程中,UncleToo給大家整理一些常見的SQL優(yōu)化技巧,避免全表掃描。一個簡單的優(yōu)化,也許能讓你的SQL執(zhí)行效率提高幾倍,甚至幾十倍。
1、避免在where子句中使用 is null 或 is not null 對字段進行判斷。
如:
select id from table where name is null
在這個查詢中,就算我們?yōu)?name 字段設置了索引,查詢分析器也不會使用,因此查詢效率底下。為了避免這樣的查詢,在數(shù)據(jù)庫設計的時候,盡量將可能會出現(xiàn) null 值的字段設置默認值,這里如果我們將 name 字段的默認值設置為0,那么我們就可以這樣查詢:
select id from table where name = 0
2、避免在 where 子句中使用 != 或 <> 操作符。
如:
select name from table where id <> 0
數(shù)據(jù)庫在查詢時,對 != 或 <> 操作符不會使用索引,而對于 < 、 <= 、 = 、 > 、 >= 、 BETWEEN AND,數(shù)據(jù)庫才會使用索引。因此對于上面的查詢,正確寫法應該是:
select name from table where id < 0
union all
select name from table where id > 0
這里我們?yōu)槭裁礇]有使用 or 來鏈接 where 后的兩個條件呢?這就是我們下面要說的第3個優(yōu)化技巧。
3、避免在 where 子句中使用 or來鏈接條件。
如:
select id from tabel where name = 'UncleToo' or name = 'PHP'
這種情況,我們可以這樣寫:
select id from tabel where name = 'UncleToo'
union all
select id from tabel where name = 'PHP'
4、少用 in 或 not in。
雖然對于 in 的條件會使用索引,不會全表掃描,但是在某些特定的情況,使用其他方法也許效果更好。如:
select name from tabel where id in(1,2,3,4,5)
像這種連續(xù)的數(shù)值,我們可以使用 BETWEEN AND,如:
select name from tabel where id between 1 and 5
5、注意 like 中通配符的使用。
下面的語句會導致全表掃描,盡量少用。如:
select id from tabel where name like'%UncleToo%'
或者
select id from tabel where name like'%UncleToo'
而下面的語句執(zhí)行效率要快的多,因為它使用了索引:
select id from tabel where name like'UncleToo%'
6、避免在 where 子句中對字段進行表達式操作。
如:
select name from table where id/2 = 100
正確的寫法應該是:
select name from table where id = 100*2
7、避免在 where 子句中對字段進行函數(shù)操作。
如:
select id from table where substring(name,1,8) = 'UncleToo'
或
select id from table where datediff(day,datefield,'2014-07-17') >= 0
這兩條語句中都對字段進行了函數(shù)處理,這樣就是的查詢分析器放棄了索引的使用。正確的寫法是這樣的:
select id from table where name like'UncleToo%'
或
select id from table where datefield <= '2014-07-17'
也就是說,不要在 where 子句中的 = 左邊進行函數(shù)、算術運算或其他表達式運算。
8、在子查詢中,用 exists 代替 in 是一個好的選擇。
如:
select name from a where id in(select id from b)
如果我們將這條語句換成下面的寫法:
select name from a where exists(select 1 from b where id = a.id)
這樣,查詢出來的結果一樣,但是下面這條語句查詢的速度要快的多。
本站僅提供存儲服務,所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權內(nèi)容,請
點擊舉報。