常用的7个SQl优化技巧
作為程序員經(jīng)常和數(shù)據(jù)庫打交道的時候還是非常頻繁的,掌握住一些Sql的優(yōu)化技巧還是非常有必要的。下面列出一些常用的SQl優(yōu)化技巧,感興趣的朋友可以了解一下。
1、注意通配符中Like的使用
以下寫法會造成全表的掃描,例如:
select id,name from userinfo where name like '%name%'
或者
select id,name from userinfo where name like '%name'
下面的寫法執(zhí)行效率快很多,因為它使用了索引
select id,name from userinfo where name like 'name%'
2、避免在where子句中對字段進(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
上面兩句都對字段進(jìn)行了函數(shù)處理,會導(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對字段進(jìn)行判斷
例如:
select id from userinfo where name is null
盡量在數(shù)據(jù)庫字段中不出現(xiàn)null,如果查詢的時候條件為 is null ,索引將不會被使用,造成查詢效率低,
因此數(shù)據(jù)庫在設(shè)計的時候,盡可能將某個字段可能為空的時候設(shè)置默認(rèn)值,那么查詢的時候可以
根據(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ù)庫在查詢時,對 != 或 <> 操作符不會使用索引,
而對于 < 、 <= 、 = 、 > 、 >= 、 BETWEEN AND,數(shù)據(jù)庫才會使用索引。
因此對于上面的查詢,正確寫法可以改為:
select name from userinfo where id < 0 union all
select name from userinfo where id > 0
7、少用in 或 not in
對于連續(xù)的數(shù)值范圍查詢盡量使用BETWEEN AND,例如:
select name from userinfo where id BETWEEN ?10 AND 70
以上只是相對來說比較常用的sql優(yōu)化技巧,當(dāng)然還有很多歡迎補(bǔ)充!
歡迎關(guān)注公眾號:DoNet技術(shù)分享平臺
閱讀原文
總結(jié)
以上是生活随笔為你收集整理的常用的7个SQl优化技巧的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 整理一些提高C#编程性能的技巧
- 下一篇: lodash中pick和omit函数介绍