0

我有一个带有索引“create_at”字段的表。我需要做一些聚合查询,但我不明白使用索引来减少范围是无效的。

所有表:

SELECT COUNT(1) FROM subscriptions

=> 412288 行

仅 2011 年:

SELECT COUNT(1) FROM subscriptions
WHERE (created_at BETWEEN '2011-01-01 00:00:00' AND '2011-12-31 23:59:59') 

=> 95217 行

按月份汇总 2011 年:

SELECT SQL_NO_CACHE MONTH(created_at) AS agg_created_at, SUM(amount) AS agg_amount 
FROM subscriptions
WHERE (created_at BETWEEN '2011-01-01 00:00:00' AND '2011-12-31 23:59:59') 
GROUP BY agg_created_at
ORDER BY agg_created_at

=> 0.1398 秒

+----+-------------+---------------+------+---------------+------+---------+------+--------+----------------------------------------------+                                                                                                         
| id | select_type | table         | type | possible_keys | key  | key_len | ref  | rows   | Extra                                        |                                                                                                         
+----+-------------+---------------+------+---------------+------+---------+------+--------+----------------------------------------------+                                                                                                         
|  1 | SIMPLE      | subscriptions | ALL  | created_at    | NULL | NULL    | NULL | 422807 | Using where; Using temporary; Using filesort |                                                                                                         
+----+-------------+---------------+------+---------------+------+---------+------+--------+----------------------------------------------+ 

与强制索引相同的查询:

SELECT SQL_NO_CACHE MONTH(created_at) AS agg_created_at, SUM(amount) AS agg_amount 
FROM subscriptions FORCE INDEX(created_at)
WHERE (created_at BETWEEN '2011-01-01 00:00:00' AND '2011-12-31 23:59:59') 
GROUP BY agg_created_at
ORDER BY agg_created_at

=> 0.1283 秒

 +----+-------------+---------------+-------+---------------+------------+---------+------+--------+----------------------------------------------+
| id | select_type | table         | type  | possible_keys | key        | key_len | ref  | rows   | Extra                                        |
+----+-------------+---------------+-------+---------------+------------+---------+------+--------+----------------------------------------------+
|  1 | SIMPLE      | subscriptions | range | created_at    | created_at | 8       | NULL | 194106 | Using where; Using temporary; Using filesort |
+----+-------------+---------------+-------+---------------+------------+---------+------+--------+----------------------------------------------+

优化器在这里看起来很聪明,因为使用索引来减少范围是无效的,但我不明白为什么。如果有人有解释?

4

0 回答 0