2、避免在 where 子句中使用 or來鏈接條件。如:select id from table where name = 'UncleToo' or name = 'php'這種情況,我們可以這樣寫:select id from table where name = 'UncleToo'union allselect id from table where name = 'PHP'
3、避免在 where 子句中使用 != 或 <> 操作符。如:select name from table where id <> 0數(shù)據(jù)庫在查詢時,對 != 或 <> 操作符不會使用索引,而對于 < 、 <= 、 = 、 > 、 >= 、 BETWEEN AND,數(shù)據(jù)庫才會使用索引。因此對于上面的查詢,正確寫法應(yīng)該是:select name from table where id < 0union allselect name from table where id > 0 4、少用 in 或 not in。雖然對于 in 的條件會使用索引,不會全表掃描,但是在某些特定的情況,使用其他方法也許效果更好。如:select name from table where id in(1,2,3,4,5)像這種連續(xù)的數(shù)值,我們可以使用 BETWEEN AND,如:select name from table where id between 1 and 55、注意 like 中通配符的使用。下面的語句會導(dǎo)致全表掃描,盡量少用。如:select id from table where name like'%UncleToo%'或者select id from table where name like'%UncleToo'而下面的語句執(zhí)行效率要快的多,因為它使用了索引:select id from table where name like'UncleToo%'6、避免在 where 子句中對字段進行表達式操作。如:select name from table where id/2 = 100正確的寫法應(yīng)該是:select name from table where id = 100*27、避免在 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ù)、算術(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)這樣,查詢出來的結(jié)果一樣,但是下面這條語句查詢的速度要快的多。新聞熱點
疑難解答
圖片精選