简体   繁体   English

如何在MySQL中的两个连续行之间没有连续ID的DATEDIFF?

[英]How to DATEDIFF in MySQL between two consecutive rows not having consecutive IDs?

Currently I have a query giving me this results coming from table "Logs": 目前,我有一个查询,给出了来自表“ Logs”的结果:

S.ID    S.INDEX   E.ID  TIME                      Secs
1       1         1     2018-05-14 16:07:48.527   
2       2         1     2018-05-14 16:08:02.967   14
3       3         1     2018-05-14 16:08:21.750   19
10      1         2     2018-05-14 16:07:46.983
11      2         2     2018-05-14 16:08:00.883   14
12      3         2     2018-05-14 16:09:19.830   79
13      4         2     2018-05-14 16:09:49.907   30
29      1         3     2018-05-14 16:08:02.490
30      2         3     2018-05-14 16:08:06.717   04

The column "Secs" was wrote by hand here, those are the values I need. “ Secs”列是在此处手工编写的,这些是我需要的值。 Already tried to use DATEDIFF but since S.ID is not consecutive (it depends on E.ID) I'm not getting the right results. 已经尝试使用DATEDIFF,但是由于S.ID不是连续的(取决于E.ID),因此无法获得正确的结果。

How can I make a query to return the right values? 如何进行查询以返回正确的值? I imagine I should take E.ID in consideration since it's the only thing that remains the same during the "same" incrementation and that if I see a 1 in S.INDEX I should reset counting. 我想我应该考虑E.ID,因为它是唯一在“相同”增量期间保持不变的东西,并且如果我在S.INDEX中看到1,则应该重置计数。

This should work, as long as the pattern I described in my original comment is guaranteed: 只要可以保证我在原始注释中描述的模式,这就可以工作:

SELECT a.*, TO_SECONDS(a.TIME) - TO_SECONDS(b.TIME) AS `Secs`
FROM theTable AS s
LEFT JOIN theTable AS b ON a.`e.id` = b.`e.id` AND a.`s.id` = b.`s.id` + 1
;

Additionally, if there is always a gap between different e.id value's s.id values, the e.id comparison is not actually needed, though still makes the intent of the query clearer. 此外,如果不同的e.id值的s.id值之间始终存在间隙,则尽管实际上可以使查询的目的更加清晰,但实际上不需要e.id比较。

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

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