Reputation: 1098
Duplicate of Mysql: Find rows, where timestamp difference is less than x
I have table as follows:
Field Type
id int(11)
user varchar(64)
date int(11)
key int(11)
Date is in time stamp format. I'm looking for a way, to find all rows, where time stamp difference between successive rows is smaller than x. Is it possible?
Upvotes: 0
Views: 811
Reputation: 1269873
This is possible, assuming timestamp means date
. Here is a version that uses a correlated subquery to get the next date
value:
select t.*
from (select t.*,
(select date
from yourtable t2
where t2.date > t.date
order by t2.date
limit 1
) as NextDate
from yourtable t
) t
where <difference calculation goes here>;
EDIT:
The above is standard SQL. In MySQL you can also do this using variables.
select t.*
from (select t.*, @nextdate as nextdate, @nextdate := date
from yourtable t
order by date desc
) t
where <difference calculation goes here>;
There are two issues that I have with this approach. First, the use of variables requires sequential processing of the result set (not a big deal in MySQL because I think this happens anyway). More importantly, the order of evaluation on the select
is not guaranteed. In other words, this probably works, but it is not guaranteed to work.
By the way, many other databases support the lead()
function which would be the "right" way to do this. Unfortunately, MySQL does not support window functions.
Upvotes: 3