首頁  >  文章  >  資料庫  >  MySQL索引不生效的解決方案

MySQL索引不生效的解決方案

黄舟
黄舟原創
2017-09-19 11:03:042311瀏覽

公司服務用的mysql,最近在查詢時時間很慢,常常會上10多秒,查看了一下查詢的執行計劃,發現索引沒有生效。

儲存引擎使用InnoDB。

 

一開始在主庫查詢,一直很好奇為什麼索引不生效,切換到備庫之後,發現備庫是有效的。

開始考慮是不是因為索引出問題,後對索引重建,發現效率高了不少。

 

簡單記錄一下比較。

mysql> explain select * from runinfo where status in (0, 2, 1, 3, 4, 7, 9, 10);
+----+-------------+---------+-------+---------------+------+---------+------+----------+-------------+
| id | select_type | table   | type  | possible_keys | key  | key_len | ref  | rows     | Extra       |
+----+-------------+---------+-------+---------------+------+---------+------+----------+-------------+
|  1 | SIMPLE      | runinfo | All   | status_2      | NULL | NULL    | NULL |  2378055 | Using where |
+----+-------------+---------+-------+---------------+------+---------+------+----------+-------------+
row in set (0.00 sec)

上面是主函式庫的執行計畫。

 比較備庫的執行計畫。

mysql> explain select * from runinfo where status in (0, 2, 1, 3, 4, 7, 9, 10);
+----+-------------+---------+-------+---------------+----------+---------+------+------+-------------+
| id | select_type | table   | type  | possible_keys | key      | key_len | ref  | rows | Extra       |
+----+-------------+---------+-------+---------------+----------+---------+------+------+-------------+
|  1 | SIMPLE      | runinfo | range | status_2      | status_2 | 4       | NULL |  116 | Using where |
+----+-------------+---------+-------+---------------+----------+---------+------+------+-------------+
row in set (0.00 sec)

 可以看出,備庫在查詢時適應到索引 status_2。

 執行如下的指令之後,問題解決。

mysql> OPTIMIZE TABLE runinfo;
+------------------+----------+----------+-------------------------------------------------------------------+
| Table            | Op       | Msg_type | Msg_text                                                          |
+------------------+----------+----------+-------------------------------------------------------------------+
| schedule.runinfo | optimize | note     | Table does not support optimize, doing recreate + analyze instead |
| schedule.runinfo | optimize | status   | OK                                                                |
+------------------+----------+----------+-------------------------------------------------------------------+
rows in set (47.13 sec)

 

#

以上是MySQL索引不生效的解決方案的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn