简体   繁体   中英

Mysql: Find rows, where timestamp difference is less than x

I've got table structure as follows:

Field       Type
id              int(11)      AI
user            varchar(64)
date            timestamp
key             int(11)

What I need to do, is find rows (from given day), where difference between two successive rows (closest timestamp (for given user) is less than 1300.

I was told, to use query like this:

select t.*
from (select t.*, @nextdate as nextdate, @nextdate := date
      from my_table t
      order by date desc
     ) t
where t.nextdate - t.date < 1300;

But it didn't seem to work. Can anyone help me solve my task?

DATEDIFF(t.netxdata, t.date) < (1300 / 3600 / 24) I assumed 1300 in in seconds, so I converted it to days which is what DATEDIFF returns. Please, be aware that this query will do a full scan of your table, which might be expensive.

try this :-

select t1.user, t1.date d1,t2.date d2 ,t1.date-t2.date
  from  (select @val:=@val+1 rowid,user,  date
           from mytable,(select @val:=0) a
       order by user,date) t1,

        (select @val1:=@val1+1 rowid,user,  date
           from mytable,(select @val1:=1) b
       order by user,date) t2

 where t1.rowid = t2.rowid
   and t1.user = t2.user
   and t1.date-t2.date < 1300;

see DEMO

This seems to be one of those rare cases where using a CURSOR is truly the most appropriate, and performant option.

However, if performance is not a consideration, you could do a correlated subquery, like the following

SELECT *, second_time - first_time
   FROM
   (
      SELECT T.user, 
             T.date      AS first_time, 
             (SELECT MIN(S.date) 
                FROM My_Table S 
                WHERE S.user = T.user
                  AND S.date > T.date
             )                         AS second_time
        FROM My_Table T
   ) G
   WHERE (second_time - first_time) < 1300

This will run very slowly on large data sets.

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