我想按时间戳对从 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 行)。有人建议我不要按每个日期实体分组,而是按UNIX_TIMESTAMP(`timestamp`)/3600
. 不幸的是,这不会导致预期的结果,结果看起来像这样
+------+-------+
| hour | value |
+------+-------+
| 13 | 21.20 |
| 13 | 21.20 |
| 13 | 21.20 |
| 13 | 21.20 |
| 13 | 21.20 |
| ... | ... |
+------+-------+
有没有办法只通过一个 group 子句对它们进行分组(这将使其更快),但返回正确的结果?