简体   繁体   English

如何找到mysql表记录之间的时间间隔和间隔长度?

[英]how to find time gaps and gap length between mysql table records?

My table looks like this:我的桌子看起来像这样:

id ID time时间
1 1 2021-07-17 17:44:26 2021-07-17 17:44:26
2 2 2021-07-17 17:44:26 2021-07-17 17:44:26
3 3 2021-07-17 17:44:26 2021-07-17 17:44:26
4 4 2021-07-17 17:44:31 2021-07-17 17:44:31
5 5 2021-07-17 17:44:31 2021-07-17 17:44:31
6 6 2021-07-17 17:44:31 2021-07-17 17:44:31
7 7 2021-07-17 17:44:36 2021-07-17 17:44:36
8 8 2021-07-17 17:44:36 2021-07-17 17:44:36
9 9 2021-07-17 17:44:36 2021-07-17 17:44:36
10 10 2021-07-17 17:44:41 2021-07-17 17:44:41
11 11 2021-07-17 17:44:41 2021-07-17 17:44:41
12 12 2021-07-17 17:44:41 2021-07-17 17:44:41
13 13 2021-07-17 17:44:51 2021-07-17 17:44:51
14 14 2021-07-17 17:44:51 2021-07-17 17:44:51
15 15 2021-07-17 17:44:51 2021-07-17 17:44:51
16 16 2021-07-17 17:44:56 2021-07-17 17:44:56
17 17 2021-07-17 17:44:56 2021-07-17 17:44:56
18 18 2021-07-17 17:44:56 2021-07-17 17:44:56
19 19 2021-07-17 17:45:02 2021-07-17 17:45:02
20 20 2021-07-17 17:45:02 2021-07-17 17:45:02
21 21 2021-07-17 17:45:02 2021-07-17 17:45:02

I have MySQL 8.0.21我有 MySQL 8.0.21

always next 3 rows have same time and then beetwen usualy is 5 seconds time gap, how to find all gap longer than 8 second and also count gap time to get something like that:总是接下来的 3 行有相同的时间,然后 beetwen 通常是 5 秒的时间间隔,如何找到所有超过 8 秒的间隔并计算间隔时间以获得类似的东西:

gap_id gap_id gap_time_start gap_time_start gap_length间隙长度
1 1 2021-07-17 17:44:41 2021-07-17 17:44:41 10 10

If you're using MySQL 8+ you can use the LEAD() window function like this:如果您使用的是 MySQL 8+,您可以像这样使用LEAD()窗口函数:

select * from (
    SELECT id as gap_id, 
        `time` as gap_start_time, 
        timediff( lead(`time`) over W, `time`) as gap_length 
        from `myTable` window w as (order by `time` asc)
    ) T where T.gap_length > 5;

Output:输出:

12, 2021-07-17 17:44:41, 00:00:10
18, 2021-07-17 17:44:56, 00:00:06

Reference: LEAD()参考: LEAD()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM