SQL 如果查询的时间不存在行,则不返回值

SQL not returning a value if no row exist for time queried

我正在编写此 SQL 查询,其中 return 是过去 24 小时内一小时内创建的记录数。我只得到那些具有非零值的时间的结果。如果没有创建任何记录,它根本不会 return 任何东西。

这是我的查询:

SELECT HOUR(timeStamp) as hour, COUNT(*) as count 
FROM `events` 
WHERE timeStamp > DATE_SUB(NOW(), INTERVAL 24 HOUR)
GROUP BY HOUR(timeStamp)
ORDER BY HOUR(timeStamp)

当前查询的输出:

+-----------------+----------+
| hour            | count    |
+-----------------+----------+
|              14 |        6 |
|              15 |        5 |
+-----------------+----------+

但我预计没有创建记录的时间为 0。我哪里错了?

一个解决方案是生成一个从 0 到 23 的 table 数字,然后将其与原始的 table 连接起来。

这里是一个使用递归查询生成小时列表的查询(如果你是运行MySQL,这需要8.0版本):

with hours as (
    select 0 hr
    union all select hr + 1 where h < 23
)
select h.hr, count(e.eventID) as cnt
from hours h
left join events e 
    on e.timestamp > now() - interval 1 day
    and hour(e.timestamp) = h.hr
group by h.hr

如果您的 RDBMS 不支持递归 CTE,那么一种选择是使用显式派生 table:

select h.hr, count(e.eventID) as cnt
from (
    select 0 hr union all select 1 union all select 2 ... union all select 23
) h
left join events e 
    on e.timestamp > now() - interval 1 day
        and hour(e.timestamp) = h.hr
group by h.hr