mysql -- froce index 使用


1.force index

1.1 好用,但是項目中慎用

最近解決mysql慢查詢問題,先把sql大概說明下

select pay_date from tableName  where add_time >'2019-05-14 23:59:59' and mark = 0 order by pay_date  limit 10;
select pay_date from tableName  where add_time >'2019-05-17 23:59:59' and mark = 0 order by pay_date  limit 10;

開發人員建了兩個索引 idx_add_time 和 idx_pay_date, 結果mysql 一直是按照idx_pay_date 索引來查找的,查詢比較慢,后來有人想到用force index(idx_add_time )解決,這樣指定按照某個索引來查詢,查詢效率很高。但是指定索引就帶來維護成本,比如哪天數據庫改動需要刪除索引index_type,如果忘記修改程序,程序必然會報錯。

1.2 詳細說明

#5000萬+的數據
#type=index說明整個索引樹都被掃描了,效果顯然不理想。 200S+ 都未查出
explain select pay_date from pss_pay_order  where add_time >'2019-03-14 23:59:59' and mark = 0 order by pay_date  limit 10;
​ #type
=range,說明索引樹僅僅被部分掃描,要優於前面那個SQL. 不到5s即可查出 explain select pay_date from pss_pay_order force index(idx_add_time) where add_time >'2019-03-14 23:59:59' and mark = 0 order by pay_date limit 10;

:explain type:index 與range 區別

range 只檢索給定范圍的行,使用一個索引來選擇行。key列顯示使用了哪個索引一般就是在你的where語句中出現了between、<、>、in等的查詢這種范圍掃描索引掃描比全表掃描要好,因為他只需要開始索引的某一點,而結束語另一點,不用掃描全部索引

index Full Index Scan,index與ALL區別為index類型只遍歷索引樹。這通常比ALL快,因為索引文件通常比數據文件小。(也就是說雖然all和index都是讀全表,但index是從索引中讀取的,而all是從硬盤中讀的

總結

mysql可能並不總會選擇合適且效率高的索引去查詢,這時適當的force index(indexname) 強制告訴mysql使用什么索引尤為重要。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM