0

我想按时间戳对从 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 子句对它们进行分组(这将使其更快),但返回正确的结果?

4

2 回答 2

1

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

SELECT
    HOUR(`timestamp`) AS `hour`,
    AVG(`somevalue`) AS `average`
FROM ...
GROUP BY
    DATE(`timestamp`),
    HOUR(`timestamp`),
ORDER BY ...
LIMIT 0, 24;
于 2013-01-20T13:47:32.463 回答
0
  1. 索引时间戳列。
  2. 试试GROUP BY DATE_FORMAT(timestamp,'%Y%m%d%H')

请注意,我自己并没有真正尝试过。

于 2013-01-20T13:11:04.443 回答