查找MySQL数据集的行之间的最小时间间隔

时间:2012-07-20 01:43:52

标签: mysql sql timestamp

我有一个MySQL表,记录了为用户收到的事件和收到事件的日期。

Date                    User

2012-01-21 18:30:02     AAA
2012-01-21 18:30:05     AAA
2012-01-21 18:30:08     AAA
2012-01-21 18:30:11     AAA
2012-01-21 18:30:15     AAA
2012-01-21 18:30:18     AAA
2012-01-21 18:30:21     AAA
2012-01-21 18:30:23     AAA
2012-01-21 18:30:26     AAA
2012-01-21 18:30:29     BBB
2012-01-21 18:30:32     BBB
2012-01-21 18:30:33     BBB
2012-01-21 18:30:37     BBB
2012-01-21 18:30:40     BBB
2012-01-21 18:30:42     BBB
2012-01-21 18:30:44     BBB
2012-01-21 18:31:01     BBB
2012-01-21 18:31:04     BBB
2012-01-21 18:31:07     BBB
2012-01-21 18:31:10     BBB

事件未按日期或用户排序。

我想找出单个用户的两个连续事件之间的时间间隔(以秒为单位)的最小值。所以结果集看起来像这样:

MIN_INTERVAL        USER

3                   AAA
5                   BBB

任何人都可以帮我提出一个生成此问题的SQL查询吗?我不认为GROUP BY会有所帮助。

3 个答案:

答案 0 :(得分:1)

这可以通过将自连接移动1个记录(按日期顺序)来实现,这将使得时间及其前一次的时间在同一行上,这样我们就可以在两者之间做出几秒的差异:

SELECT 
    a.user,
    MIN(TIMESTAMPDIFF(SECOND, b.date, a.date)) AS mindiff
FROM
(
    SELECT user, date, @val1:=@val1+1 AS rn
    FROM tbl
    CROSS JOIN (SELECT @val1:=0) AS val1_init
    ORDER BY date
) a
INNER JOIN
(
    SELECT user, date, @val2:=@val2+1 AS rn
    FROM tbl
    CROSS JOIN (SELECT @val2:=1) AS val2_init
    ORDER BY date
) b ON a.rn = b.rn
GROUP BY a.user

SQLFiddle Demo


Intermediate Results (Before GROUP BY)

答案 1 :(得分:1)

简单版本可能不是最快的?

SELECT t1.user, MIN(TIMESTAMPDIFF(SECOND, t1.date, t2.date))
FROM tbl AS t1
JOIN tbl AS t2 ON t1.user = t2.user
WHERE t1.date < t2.date
GROUP BY t1.user

答案 2 :(得分:0)

在mysql中,您需要使用自联接和两个分组来执行此操作:

select t.user, min(diff)
from (select t.user, unix_timestamp(tnext.date) - unix_timestamp(t.date) as diff
      from t join
           tnext
           on t.user = tnext.user and
              t.date < tnext.date
      group by t.user, t.date
     ) t
group by user

内部子查询下次查找并减去值以获取diff。外部返回最小的差异。