共計 2627 個字符,預計需要花費 7 分鐘才能閱讀完成。
本篇文章為大家展示了怎么進行 mysql 索引覆蓋掃描優化,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
覆蓋掃描即直接在索引中掃描出結果返回給客戶端,不需要根據索引再去表上掃描結果,這種掃描方式效率高。當 extra 列出現 Using index 時即為覆蓋掃描
現生產環境有個語句要優化,
select create_day,remarks_format,count(*) from CDM.cdm_account_itemized GROUP BY create_day,remarks_format;
執行需要 20 秒,看下執行計劃
mysql explain select create_day,remarks_format,count(*) from CDM.cdm_account_itemized GROUP BY create_day,remarks_format;
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
| 1 | SIMPLE | cdm_account_itemized | ALL | NULL | NULL | NULL | NULL | 10123349 | Using temporary; Using filesort |
1 row in set (0.00 sec)
走了全表掃描并使用了 Using filesort 臨時文件排序;create_day 和 remarks_format 字段都是有索引的,但并沒有走索引
mysql explain select create_day,count(*) from CDM.cdm_account_itemized GROUP BY create_day ;
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
| 1 | SIMPLE | cdm_account_itemized | index | biz_account_itemized_create_day | biz_account_itemized_create_day | 25 | NULL | 10123349 | Using index |
+—-+————-+———————-+——-+———————————+———————————+———+——+———-+————-+
1 row in set (0.00 sec)
只針對 create_day 進行分組統計的時候可以看到走的索引覆蓋掃描 Using index,執行只要 5 秒
mysql explain select remarks_format,count(*) from CDM.cdm_account_itemized GROUP BY remarks_format;
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
| 1 | SIMPLE | cdm_account_itemized | index | biz_account_itemized_create_day | biz_account_itemized_create_day | 25 | NULL | 10123349 | Using index |
1 row in set (0.00 sec)
只針對 remarks_format 進行分組統計的時候可以看到也走的索引覆蓋掃描 Using index,執行只要 4 秒
看樣子只能增加個組合索引了
mysql alter table CDM.cdm_account_itemized add index create_day_remarks_format(create_day,remarks_format)
加完索引再看下執行計劃
mysql explain select create_day,remarks_format,count(*) from CDM.cdm_account_itemized GROUP BY create_day,remarks_format;
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
| 1 | SIMPLE | cdm_account_itemized | index | create_day_remarks_format | create_day_remarks_format | 793 | NULL | 10123349 | Using index |
1 row in set (0.00 sec)
這個時候執行計劃走的是 create_day_remarks_format 索引的索引覆蓋掃描 Using index,但是執行還是需要 20 秒。這可能和統計信息有關,實際的執行計劃和 explain 出來的不一樣
ANALYZE 收集下統計信息
mysql ANALYZE table CDM.cdm_account_itemized;
| Table | Op | Msg_type | Msg_text |
| CDM.cdm_account_itemized | analyze | status | OK |
1 row in set (1.64 sec)
再次執行只要 5 秒多就返回結果了
mysql select create_day,remarks_format,count(*) from CDM.cdm_account_itemized GROUP BY create_day,remarks_format;
5.580s
結論:select 后面的字段在同一個索引中才會走索引覆蓋掃描
上述內容就是怎么進行 mysql 索引覆蓋掃描優化,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注丸趣 TV 行業資訊頻道。