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