日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

8個SQL語句常用優(yōu)化技巧

 平民小白 2018-01-31
要提高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è)置了索引,查詢分析器也不會使用,因此查詢效率底下。為了避免這樣的查詢,在數(shù)據(jù)庫設(shè)計的時候,盡量將可能會出現(xiàn) null 值的字段設(shè)置默認值,這里如果我們將 name 字段的默認值設(shè)置為0,那么我們就可以這樣查詢:

select id from table where name = 0


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

如:

select name from table where id <> 0

數(shù)據(jù)庫在查詢時,對 != 或 <> 操作符不會使用索引,而對于 < 、 <= 、 = 、 > 、 >= 、 BETWEEN AND,數(shù)據(jù)庫才會使用索引。因此對于上面的查詢,正確寫法應(yīng)該是:

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 中通配符的使用。

下面的語句會導(dǎo)致全表掃描,盡量少用。如:

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

正確的寫法應(yīng)該是:

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ù)、算術(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é)果一樣,但是下面這條語句查詢的速度要快的多。

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多