简体   繁体   中英

MySQL: Find successive rows, where timestamp difference is less than x

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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