按日期对MYSQL结果行进行分组

时间:2013-01-20 13:03:11

标签: mysql performance group-by

我希望按时间戳的小时对从MYSQL数据库中提取的结果进行分组。时间戳以2012-12-14 03:19:09格式存储在表中。我使用查询

SELECT
    HOUR(`timestamp`) AS `hour`,
    AVG(`somevalue`) AS `average`
FROM ...
GROUP BY
    HOUR(`timestamp`),
    DAY(`timestamp`),
    MONTH(`timestamp`),
    WEEK(`timestamp`),
    YEAR(`timestamp`)
ORDER BY ...
LIMIT 0, 24;

这样可行,并返回正确的行和值......

+------+-------+
| hour | value |
+------+-------+
| 13   | 21.16 | 
| 12   | 21.11 |
| 11   | 20.88 |
| 10   | 20.93 |
|  9   | 20.87 |
|  8   | 20.89 |
| ...  | ...   |
+------+-------+ 

...但非常慢(表包含~90k行)。我given the advice不是按每个日期实体分组,而是按UNIX_TIMESTAMP(`timestamp`)/3600分组。遗憾的是,这并没有产生预期的结果,结果看起来像这样

+------+-------+
| hour | value |
+------+-------+
| 13   | 21.20 |
| 13   | 21.20 |
| 13   | 21.20 |
| 13   | 21.20 |
| 13   | 21.20 |
| ...  | ...   |
+------+-------+ 

有没有办法只通过一个组子句对它们进行分组(这会使它更快),但是会返回正确的结果吗?

2 个答案:

答案 0 :(得分:1)

而不是按日期和小时使用分组

SELECT
    HOUR(`timestamp`) AS `hour`,
    AVG(`somevalue`) AS `average`
FROM ...
GROUP BY
    DATE(`timestamp`),
    HOUR(`timestamp`),
ORDER BY ...
LIMIT 0, 24;

答案 1 :(得分:0)

  1. 索引时间戳列。
  2. 试试GROUP BY DATE_FORMAT(timestamp,'%Y%m%d%H')
  3. 请注意,我自己并没有真正尝试过。