09.27 Mysql百萬級以上查詢速度我們這樣做(上)

1.應儘量避免在 where 子句中使用!=或<>操作符,否則將引擎放棄使用索引而進行全表掃描。

2.對查詢進行優化,應儘量避免全表掃描,首先應考慮在 where 及 order by 涉及的列上建立索引。

3.應儘量避免在 where 子句中對字段進行 null 值判斷(或儘量避免null的設置),否則將導致引擎放棄使用索引而進行全表掃描,如:

select field from t where field is null

可以在field上設置默認值0,確保表中field列沒有null值,然後這樣查詢:

select field from t where field=0

4.應儘量避免在 where 子句中使用 or 來連接條件,否則將導致引擎放棄使用索引而進行全表掃描,如:

select field from t where field=10 or field=20

可以這樣查詢:

select field from t where field=10

union all (全鏈接)

select field from t where field=20

5.下面的查詢也將導致全表掃描:(不能前置百分號)

select id from t where name like ‘%field%’

若要提高效率,可以考慮全文檢索。

6.in 和 not in 也要慎用,否則會導致全表掃描,如:

select id from t where num in(1,2,3)

對於連續的數值,能用 between 就不要用 in 了:

select id from t where num between 1 and 3

select xx,phone FROM send a JOIN (

select '13xxxxx' phone union select '13xxxx' ………… UNION SELECT '13xxx' ) b

on a.Phone=b.phone

--替代下面 很多數據隔開的時候

in('13xxx','13xxxxx','13xxxx'…………)

7.如果在 where 子句中使用參數,也會導致全表掃描。因為SQL只有在運行時才會解析局部變量,但優化程序不能將訪問計劃的選擇推遲到運行時;它必須在編譯時進行選擇。然 而,如果在編譯時建立訪問計劃,變量的值還是未知的,因而無法作為索引選擇的輸入項。如下面語句將進行全表掃描:

select id from t where num=@num 可以改為強制查詢使用索引:

select id from t with(index(索引名)) where num=@num

8.應儘量避免在 where 子句中對字段進行表達式操作,這將導致引擎放棄使用索引而進行全表掃描。如:

select id from t where num/2=100

應改為:

select id from t where num=100*2

9.應儘量避免在where子句中對字段進行函數操作,這將導致引擎放棄使用索引而進行全表掃描。如:

select id from t where substring(name,1,3)=’abc’–name以abc開頭的id

select id from t where datediff(day,createdate,’2018-11-30′)=0–’2018-11-30′生成的id

應改為:

select id from t where name like ‘abc%’

select id from t where createdate>=’2018-11-30′ and createdate2018-12-1

10.不要在 where 子句中的“=”左邊進行函數、算術運算或其他表達式運算,否則系統將可能無法正確使用索引。

總結於數據庫技術內幕-感興趣可直接購買


分享到:


相關文章: