日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

常用的7个SQl优化技巧

發布時間:2023/12/10 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 常用的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优化技巧的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。