【问题标题】:mysql indexes and optimizations, Using where; using temporary; using filesortmysql 索引和优化,使用 where;使用临时的;使用文件排序
【发布时间】:2012-05-23 11:46:12
【问题描述】:

哪些表和列应该有索引?我在 flow_permanent_id 和 entry_id 上有一个索引,但它似乎在使用文件排序?

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

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)

【问题讨论】:

    标签: mysql count indexing group-by filesort


    【解决方案1】:

    为避免文件排序,您需要在 (flow_permanent_id, entry_id) 上创建一个复合索引,以便 MySQL 可以将索引用于 WHERE 和 GROUP BY。

    【讨论】:

      【解决方案2】:

      首先 - 使用 COUNT(1) 而不是 COUNT( * ),在某些情况下可能会提高性能。永远不要使用 COUNT(*)。

      第二:看起来您使用了索引,它列在 EXPLAIN 输出的“键”列中。 您的“GROUP BY”是导致文件排序的原因。通常是 ORDER BY 是罪魁祸首,但我看到 GROUP BY 也可以做到这一点。

      希望这会有所帮助。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-08
      • 2018-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-13
      • 2013-06-13
      相关资源
      最近更新 更多