mysql索引和优化,使用where;暂时使用;使用filesort

时间:2012-05-15 22:23:20

标签: mysql count indexing group-by filesort

哪些表和列应该有索引?我有一个关于flow_permanent_id和entry_id的索引,但似乎是在使用filesort?

我可以做些什么来优化它?

mysql> explain SELECT COUNT(*) AS count_all, entry_id AS entry_id FROM `votes` WHERE `votes`.`flow_permanent_id` = '4fab490cdc1c82cfa800000a' GROUP BY entry_id;
+----+-------------+-------+------+----------------------------------+----------------------------------+---------+-------+------+----------------------------------------------+
| id | select_type | table | type | possible_keys                    | key                              | key_len | ref   | rows | Extra                                        |
+----+-------------+-------+------+----------------------------------+----------------------------------+---------+-------+------+----------------------------------------------+
|  1 | SIMPLE      | votes | ref  | index_votes_on_flow_permanent_id | index_votes_on_flow_permanent_id | 74      | const |    1 | Using where; Using temporary; Using filesort |
+----+-------------+-------+------+----------------------------------+----------------------------------+---------+-------+------+----------------------------------------------+
1 row in set (0.00 sec)

2 个答案:

答案 0 :(得分:7)

为了避免使用filesort,你需要一个复合索引(flow_permanent_identry_id),以便MySQL可以使用WHERE和GROUP BY的索引。

答案 1 :(得分:1)

首先 - 使用COUNT(1)而不是COUNT(*),在某些情况下可以提高性能。切勿使用COUNT(*)。

第二:看起来你使用了索引,它列在EXPLAIN输出的'key'列中。 您的“GROUP BY”是导致filesort的东西。通常它是ORDER BY那是罪魁祸首,但我也看到GROUP BY也能做到这一点。

希望这有帮助。

相关问题