mysql -- froce index 使用

1.force index

1.1 好用,可是項目中慎用

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

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,若是忘記修改程序,程序必然會報錯。sql

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等的查詢這種範圍掃描索引掃描比全表掃描要好,由於他只須要開始索引的某一點,而結束語另外一點,不用掃描所有索引spa

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

總結blog

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

相關文章
相關標籤/搜索