MySQL - Find the largest time difference between consecutive datetimes
This query will compute time differences between successive rows and display the largest one -- the length of the winning streak. If you need the whole row, you'll need Gordon's query.
SELECT MAX(diff)
FROM (
SELECT TIMEDIFF(datetime,@prev) AS diff,
(@prev:=datetime) AS datetime
FROM resets,
(SELECT @prev:=(SELECT MIN(datetime) FROM resets)) AS init
ORDER BY datetime
) AS diffs
How does this work?
First of all, it's a cross-join between a one-row query and your table. The one-row query is this:
(SELECT @prev:=(SELECT MIN(datetime) FROM resets))
It sets the user-defined value @prev
to the lowest/earliest datetime
in the table. This is a MySQL trick to initialize a user-defined variable at the beginning of the query.
Then, the SELECT clause has two columns in it:
SELECT TIMEDIFF(datetime,@prev) AS diff,
(@prev:=datetime) AS datetime
The first one takes the time difference between the present row's datetime
and the value of @prev
. The second one updates the value of @prev
to the present row's datetime
.
So the inner query spits out a list of the timestamps and the difference to the preceding timestamp in ORDER BY datetime
.
The outer query SELECT MAX(diff)
grabs the largest value of diff -- the longest winning streak -- from the inner query.
Let's be clear: This is MySQL-specific monkey business. Pure SQL is supposed to be declarative, not procedural. But this trick with the user-defined @prev
variable lets us mix declarative and procedural code in a useful way, even if it's somewhat obscure.
You can calculate the next datetime using a correlated subquery and then find the biggest by sorting:
select r.*
from (select r.*,
(select datetime
from resets r2
where r2.datetime > r.datetime
order by datetime
limit 1
) as next_datetime
from resets r
) r
order by timestampdiff(second, datetime, next_datetime) desc
limit 1;