作為程序員經(jīng)常和數(shù)據(jù)庫(kù)打交道的時(shí)候還是非常頻繁的脯倒,掌握住一些Sql的優(yōu)化技巧還是非常有必要的撮躁。下面列出一些常用的SQl優(yōu)化技巧漱病,感興趣的朋友可以了解一下。
1把曼、注意通配符中Like的使用
以下寫法會(huì)造成全表的掃描杨帽,例如:
select id,name from userinfo where name like '%name%'
或者
select id,name from userinfo where name like '%name'
下面的寫法執(zhí)行效率快很多,因?yàn)樗褂昧怂饕?/p>
select id,name from userinfo where name like 'name%'
2嗤军、避免在where子句中對(duì)字段進(jìn)行函數(shù)操作
比如:
select id from userinfo where substring(name,1,6) = 'xiaomi'
或者
select id from userinfo where datediff(day,datefield,'2017-05-17') >= 0
上面兩句都對(duì)字段進(jìn)行了函數(shù)處理睦尽,會(huì)導(dǎo)致查詢分析器放棄了索引的使用。
正確的寫法:
select id from userinfo where name like'xiaomi%'
select id from userinfo where datefield <= '2017-05-17'
通俗理解就是where子句‘=’ 左邊不要出現(xiàn)函數(shù)型雳、算數(shù)運(yùn)算或者其他表達(dá)式運(yùn)算
3当凡、在子查詢當(dāng)中,盡量用exists代替in
select name from userinfo a where id in(select id from userinfo b)
可以改為
select name from userinfo a where exists(select 1 from userinfo b where id = a.id)
下面的查詢速度比in查詢的要快很多纠俭。
4沿量、where子句中盡量不要使用is null 或 is not null對(duì)字段進(jìn)行判斷
例如:
select id from userinfo where name is null
盡量在數(shù)據(jù)庫(kù)字段中不出現(xiàn)null,如果查詢的時(shí)候條件為 is null 冤荆,索引將不會(huì)被使用朴则,造成查詢效率低,
因此數(shù)據(jù)庫(kù)在設(shè)計(jì)的時(shí)候钓简,盡可能將某個(gè)字段可能為空的時(shí)候設(shè)置默認(rèn)值乌妒,那么查詢的時(shí)候可以
根據(jù)默認(rèn)值進(jìn)行查詢,比如name字段設(shè)置為0外邓,查詢語句可以修改為
select id from userinfo where name=0
5撤蚊、避免在where子句使用or作為鏈接條件
例如:
select id from userinfo where name='xiaoming' or name='xiaowang'
可以改寫為:
select id from userinfo where name = 'xiaoming' union all
select id from userinfo where name = 'xiaowang'
6、避免在 where 子句中使用 != 或 <> 操作符损话。
例如:
select name from userinfo where id <> 0
說明:數(shù)據(jù)庫(kù)在查詢時(shí)侦啸,對(duì) != 或 <> 操作符不會(huì)使用索引槽唾,
而對(duì)于 < 、 <= 光涂、 = 庞萍、 > 、 >= 忘闻、 BETWEEN AND钝计,數(shù)據(jù)庫(kù)才會(huì)使用索引。
因此對(duì)于上面的查詢齐佳,正確寫法可以改為:
select name from userinfo where id < 0 union all
select name from userinfo where id > 0
7葵蒂、少用in 或 not in
對(duì)于連續(xù)的數(shù)值范圍查詢盡量使用BETWEEN AND,例如:
select name from userinfo where id BETWEEN ?10 AND 70
以上只是相對(duì)來說比較常用的sql優(yōu)化技巧重虑,當(dāng)然還有很多歡迎補(bǔ)充!
歡迎關(guān)注公眾號(hào):DoNet技術(shù)分享平臺(tái)