如何通过一次查询获取上一小时、上一天和上个月的数据?

How to get data from last hour, last day and last month with one query?

我正在记录已发送到我的 API 的查询,如下所示:

id  |  timestamp
----+---------------------
1   |  2015-01-19 18:01:47
2   |  2015-01-19 20:41:37
3   |  2015-01-20 14:15:06
4   |  2015-01-21 13:02:51
5   |  2015-01-23 05:02:12

现在,我需要知道在过去的 60 分钟、24 小时和 30 天内进行了多少查询,并将其分组:

HOURLY | DAILY | MONTHLY
-------+-------+--------
0      | 1     | 5

这可以在一次查询中完成吗?

编辑:

我已经使用了这里的建议,并尝试了一些符合逻辑的事情,直到它按照我想要的方式工作。

SELECT SUM(CASE WHEN DATE_SUB(NOW(), interval 1 HOUR) <= `TIMESTAMP` THEN 1 ELSE 0 END) HOURLY,
       SUM(CASE WHEN DATE_SUB(NOW(), interval 1 DAY) <= `TIMESTAMP` THEN 1 ELSE 0 END) DAILY,
       SUM(CASE WHEN DATE_SUB(NOW(), interval 1 MONTH) <= `TIMESTAMP` THEN 1 ELSE 0 END) MONTHLY
FROM `REQUESTS`;

非常感谢你们的帮助!

select sum(timestamp >= now() - interval 1 hour) as hour,
       sum(timestamp >= now() - interval 1 day) as day,
       sum(timestamp >= now() - interval 1 month) as month
from your_table

SQLFiddle demo

select sum(case when timestamp between now() - interval 1 hour and now() then 1 else 0) hourly,
       sum(case when timestamp between now() - interval 1 day and now() then 1 else 0) daily,
       sum(case when timestamp between now() - interval 1 month and now() then 1 else 0) monthly
from   your_table

已编辑...

您可以在此处使用的另一个巧妙技巧是 SUM() 函数,其中仅包含一个布尔表达式。当您这样做时,MySQL 将有效地计算满足条件的行数。所以,通过使用类似的东西:

SUM(timeCol >= (NOW() - INTERVAL 1 HOUR))

它只会计算在过去一小时内具有时间戳的行数。试试这个查询:

SELECT SUM(timecol >= (NOW() - INTERVAL 1 HOUR)) AS hourly,
  SUM(timeCol >= (NOW() - INTERVAL 1 DAY)) AS daily,
  SUM(timeCol >= (NOW() - INTERVAL 1 MONTH)) AS monthly
FROM myTable;

它在 SQL Fiddle 对我有用。

编辑

如果您的 table 有未来的日期,上述解决方案将不起作用,所以如果您想确保只在最后一次获取值超过当前时间的小时、天或月,只需添加一个 where 子句:

SELECT SUM(timecol >= (NOW() - INTERVAL 1 HOUR)) AS hourly,
  SUM(timeCol >= (NOW() - INTERVAL 1 DAY)) AS daily,
  SUM(timeCol >= (NOW() - INTERVAL 1 MONTH)) AS monthly
FROM myTable
WHERE timeCol <= NOW();

这是更新后的 Fiddle,它有一条无效记录表明它有效。