使用 MySQL 查询定期统计时间范围内的记录

Using a MySQL query to count records with time ranges at regular intervals

给定一个 MySQL table 来跟踪访问者在某个位置停留的时间,什么是 suitable 查询以 5 分钟为间隔计算访问者总数一天的课程?

+-----------------+------------------+------+-----+---------+-------+
| Field           | Type             | Null | Key | Default | Extra |
+-----------------+------------------+------+-----+---------+-------+
| end_timestamp   | int(10) unsigned | NO   | PRI | NULL    |       |
| start_timestamp | int(10) unsigned | NO   | PRI | NULL    |       |
| visitor_id      | int(10) unsigned | NO   | PRI | NULL    |       |
| location_id     | int(10) unsigned | NO   | PRI | NULL    |       |
+-----------------+------------------+------+-----+---------+-------+

例如结果可能如下所示:

+---------------------+-------------------+
| Timestamp           | COUNT(visitor_id) |
+---------------------+-------------------+
| 2020-01-01 00:00:00 | 45                |
| 2020-01-01 00:05:00 | 49                |
| 2020-01-01 00:10:00 | 37                |
...

这是我目前正在计算的 post-查询,但希望通过将其作为数据库查询的一部分将部分工作转移到 MySQL 服务器。

如果你是运行 MySQL 8.0,你可以使用递归查询生成区间,然后把你的table带上left join,最后聚合.

以下查询为您提供当天所需的信息(您可以根据需要将 current_date 更改为其他日期):

with all_ts as (
    select current_date ts
    union all
    select ts + interval 5 minute 
    from all_ts 
    where ts < current_date + interval 1 day
)
select a.ts, count(t.visitor_id) no_visitors
from all_ts a
left join mytable t
    on  t.start_timestamp >= a.ts
    and t.end_timestamp   <  a.ts 
group by a.ts

如果您将日期存储为 unix 时间戳,您可以按如下方式更改 left join

left join mytable t
    on  t.start_timestamp >= unix_timestamp(a.ts)
    and t.end_timestamp   <  unix_timestamp(a.ts)