公司服务用的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索引不生效的解决办法的详细内容。