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

前端 未结 3 1816
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-24 07:35

I\'ve got table structure as follows:

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


        
3条回答
  •  暖寄归人
    2021-01-24 08:05

    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.

提交回复
热议问题