要提高SQL語句的執(zhí)行效率,最常見的方法就是建立索引,以及盡量避免全表掃描。在本章MySQL教程中,UncleToo給大家整理一些常見的SQL優(yōu)化技巧,避免全表掃描。一個(gè)簡(jiǎn)單的優(yōu)化,也許能讓你的SQL執(zhí)行效率提高幾倍,甚至幾十倍。 1、避免在where子句中使用 is null 或 is not null 對(duì)字段進(jìn)行判斷。 如: select id from table where name is null 在這個(gè)查詢中,就算我們?yōu)?name 字段設(shè)置了索引,查詢分析器也不會(huì)使用,因此查詢效率底下。為了避免這樣的查詢,在數(shù)據(jù)庫設(shè)計(jì)的時(shí)候,盡量將可能會(huì)出現(xiàn) null 值的字段設(shè)置默認(rèn)值,這里如果我們將 name 字段的默認(rèn)值設(shè)置為0,那么我們就可以這樣查詢: select id from table where name = 0 2、避免在 where 子句中使用 != 或 <> 操作符。 如: select name from table where id <> 0 數(shù)據(jù)庫在查詢時(shí),對(duì) != 或 <> 操作符不會(huì)使用索引,而對(duì)于 < 、 <= 、 = 、 > 、 >= 、 BETWEEN AND,數(shù)據(jù)庫才會(huì)使用索引。因此對(duì)于上面的查詢,正確寫法應(yīng)該是: select name from table where id < 0 union all select name from table where id > 0 這里我們?yōu)槭裁礇]有使用 or 來鏈接 where 后的兩個(gè)條件呢?這就是我們下面要說的第3個(gè)優(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。 雖然對(duì)于 in 的條件會(huì)使用索引,不會(huì)全表掃描,但是在某些特定的情況,使用其他方法也許效果更好。如: 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 中通配符的使用。 下面的語句會(huì)導(dǎo)致全表掃描,盡量少用。如: select id from tabel where name like'%UncleToo%' 或者 select id from tabel where name like'%UncleToo' 而下面的語句執(zhí)行效率要快的多,因?yàn)樗褂昧怂饕?br> select id from tabel where name like'UncleToo%' 6、避免在 where 子句中對(duì)字段進(jìn)行表達(dá)式操作。 如: select name from table where id/2 = 100 正確的寫法應(yīng)該是: select name from table where id = 100*2 7、避免在 where 子句中對(duì)字段進(jìn)行函數(shù)操作。 如: select id from table where substring(name,1,8) = 'UncleToo' 或 select id from table where datediff(day,datefield,'2014-07-17') >= 0 這兩條語句中都對(duì)字段進(jìn)行了函數(shù)處理,這樣就是的查詢分析器放棄了索引的使用。正確的寫法是這樣的: select id from table where name like'UncleToo%' 或 select id from table where datefield <= '2014-07-17' 也就是說,不要在 where 子句中的 = 左邊進(jìn)行函數(shù)、算術(shù)運(yùn)算或其他表達(dá)式運(yùn)算。 8、在子查詢中,用 exists 代替 in 是一個(gè)好的選擇。 如: 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) 這樣,查詢出來的結(jié)果一樣,但是下面這條語句查詢的速度要快的多。 |
|