使用SUM时提高MySQL查询性能

时间:2011-12-22 17:30:20

标签: mysql

我有一个用户生成内容表,其中包含状态的ENUM格式列。 (待处理,已批准,已批准 - 自动或已拒绝)为了按状态密切关注最近内容的数量,我使用以下查询:

mysql> SELECT DATE(dt_submitted) AS date, 
              COUNT(*) AS count,
              SUM(IF(status='Approved', 1, 0)) as approved,
              SUM(IF(status='Approved-auto', 1, 0)) as approved_auto,
              SUM(IF(status='Rejected', 1, 0)) as rejected,
              SUM(IF(status='Pending', 1, 0)) as pending
       FROM post
       WHERE dt_submitted > DATE_SUB(CURDATE(), INTERVAL 30 DAY)
       GROUP BY date;
+------------+-------+----------+---------------+----------+---------+
| date       | count | approved | approved_auto | rejected | pending |
+------------+-------+----------+---------------+----------+---------+
| 2011-11-22 |   131 |      124 |             0 |        7 |       0 | 
| 2011-11-23 |   116 |      114 |             0 |        2 |       0 | 
...
| 2011-12-21 |   690 |      674 |             5 |       11 |       0 | 
| 2011-12-22 |    80 |       75 |             0 |        4 |      38 | 
+------------+-------+----------+---------------+----------+---------+
31 rows in set (0.60 sec)

这几乎是完美的,但我很挑剔,想看看我是否可以加快速度。 (此服务器上0.6秒的速度很慢,并且表格经常更改以担心将静态日期传递给缓存结果。)

如果我解析查询,它没有使用任何索引(status被索引)。 (这是因为它指的是为SUM创建的临时表吗?)

explain SELECT DATE(dt_submitted) AS date, COUNT(*) AS count, SUM(IF(status='Approved', 1, 0)) as approved, SUM(IF(status='Approved-auto', 1, 0)) as approved_auto, SUM(IF(status='Rejected', 1, 0)) as rejected, SUM(IF(status='Pending', 1, 0)) as pending FROM post WHERE dt_submitted > DATE_SUB(CURDATE(), INTERVAL 30 DAY)  GROUP BY date;
+----+-------------+-------+------+---------------+------+---------+------+--------+----------------------------------------------+
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows   | Extra                                        |
+----+-------------+-------+------+---------------+------+---------+------+--------+----------------------------------------------+
|  1 | SIMPLE      | post  | ALL  | NULL          | NULL | NULL    | NULL | 529902 | Using where; Using temporary; Using filesort | 
+----+-------------+-------+------+---------------+------+---------+------+--------+----------------------------------------------+
1 row in set (0.00 sec)

那么我可以做些什么来优化表格或重写查询以使其更快?或者此查询是否仅受可用系统资源速度的限制?

编辑:dt_submitted未编入索引。

1 个答案:

答案 0 :(得分:0)

仔细检查是否已将相应的列编入索引。

(如编辑中所述,我没有仔细检查我的索引。一旦我索引了相应的列,问题就解决了。)