共計 2434 個字符,預計需要花費 7 分鐘才能閱讀完成。
這篇文章將為大家詳細講解有關常用 SQL 語句優化技巧有哪些,丸趣 TV 小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
具體如下:
除了建立索引之外,保持良好的 SQL 語句編寫習慣將會降低 SQL 性能問題發生。
①通過變量的方式來設置參數
好:
stringsql = select * from people p where p.id = ?
壞:
stringsql = select * from people p where p.id = +id;
數據庫的 SQL 文解析和執行計劃會保存在緩存中,但是 SQL 文只要有變化,就得重新解析。
“…where p.id =”+id 的方式在 id 值發生改變時需要重新解析,這會耗費時間。
②不要使用 select *
好:
stringsql = select people_name,pepole_age from people
壞:
stringsql = select * from people
使用 select * 的話會增加解析的時間,另外會把不需要的數據也給查詢出來,數據傳輸也是耗費時間的,
比如 text 類型的字段通常用來保存一些內容比較繁雜的東西,如果使用 select * 則會把該字段也查詢出來。
③謹慎使用模糊查詢
好:
stringsql = select * from people p where p.id like parm1%
壞:
stringsql = select * from people p where p.id like %parm1%
當模糊匹配以 % 開頭時,該列索引將失效,若不以 % 開頭,該列索引有效。
④不要使用列號
好:
stringsql = select people_name,pepole_age from people order by name,age
壞:
stringsql = select people_name,pepole_age from people order by 6,8
使用列號的話,將會增加不必要的解析時間。
⑤優先使用 UNION ALL,避免使用 UNION
好:
stringsql = select name from student union all select name from teacher
壞:
stringsql = select name from student union select name from teacher
UNION 因為會將各查詢子集的記錄做比較,故比起 UNION ALL,通常速度都會慢上許多。一般來說,如果使用 UNION ALL 能滿足要求的話,務必使用 UNION ALL。還有一種情況,如果業務上能夠確保不會出現重復記錄。
⑥在 where 語句或者 order by 語句中避免對索引字段進行計算操作
好:
stringsql = select people_name,pepole_age from people where create_date=date1
壞:
stringsql = select people_name,pepole_age from people where trunc(create_date)=date1
當在索引列上進行操作之后,索引將會失效。正確做法應該是將值計算好再傳入進來。
⑦使用 not exist 代替 not in
好:
stringsql = select * from orders where customer_name not exist (select customer_name from customer)
壞:
stringsql = select * from orders where customer_name not in(select customer_name from customer)
如果查詢語句使用了 not in 那么內外表都進行全表掃描,沒有用到索引;而 not extsts 的子查詢依然能用到表上的索引。
⑧ exist 和 in 的區別
in 是把外表和內表作 hash 連接,而 exists 是對外表作 loop 循環,每次 loop 循環再對內表進行查詢。因此,in 用到的是外表的索引,exists 用到的是內表的索引。
如果查詢的兩個表大小相當,那么用 in 和 exists 差別不大。
如果兩個表中一個較小,一個是大表,則子查詢表大的用 exists,子查詢表小的用 in:
例如:表 A(小表),表 B(大表)
1:
select * from A where cc in (select cc from B)
效率低,用到了 A 表上 cc 列的索引;
select * from A where exists(select cc from B where cc=A.cc)
效率高,用到了 B 表上 cc 列的索引。
2:
select * from B where cc in (select cc from A)
效率高,用到了 B 表上 cc 列的索引;
select * from B where exists(select cc from A where cc=B.cc)
效率低,用到了 A 表上 cc 列的索引。
⑨避免在索引列上做如下操作:
◆避免在索引字段上使用,!=
◆避免在索引列上使用 IS NULL 和 IS NOT NULL
◆避免在索引列上出現數據類型轉換(比如某字段是 String 類型,參數傳入時是 int 類型)
當在索引列上使用如上操作時,索引將會失效,造成全表掃描。
⑩復雜操作可以考慮適當拆成幾步
有時候會有通過一個 SQL 語句來實現復雜業務的例子出現,為了實現復雜的業務,嵌套多級子查詢。造成 SQL 性能問題。對于這種情況可以考慮拆分 SQL,通過多個 SQL 語句實現,或者把部分程序能完成的工作交給程序完成。
關于“常用 SQL 語句優化技巧有哪些”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。