我正在使用MySQL 5.7
计算连续行之间的时间差(以秒为单位)。我有几个问题
@diff
列以排除0
或大于60
秒的值?每当我尝试添加WHERE
子句时,都会出现错误。SUM
列@diff
来获取总时间?SELECT @diff AS start,
created AS end,
IF(@diff = 0, 0, UNIX_TIMESTAMP(`created`) - UNIX_TIMESTAMP(@diff)) AS diff,
@diff := created AS endtime
FROM events,
(SELECT @diff := 0) AS x
ORDER BY events.created
events
Desc | Timestamp
-------------------------------
Event 1 | 2019-01-03 17:21:03
Event 2 | 2019-01-03 17:21:03
Event 3 | 2019-01-03 17:21:03
Event 4 | 2019-01-03 17:21:14
Event 5 | 2019-01-03 17:21:16
Event 6 | 2019-01-03 17:25:46
start | end | diff | endtime
-------------------------------------------------------------------------
0 | 2019-01-03 17:21:03 | 0 | 2019-01-03 17:21:03
2019-01-03 17:21:03 | 2019-01-03 17:21:03 | 0.000000 | 2019-01-03 17:21:03
2019-01-03 17:21:03 | 2019-01-03 17:21:03 | 0.000000 | 2019-01-03 17:21:03
2019-01-03 17:21:03 | 2019-01-03 17:21:14 | 11.00000 | 2019-01-03 17:21:14
2019-01-03 17:21:14 | 2019-01-03 17:21:16 | 2.000000 | 2019-01-03 17:21:16
2019-01-03 17:21:16 | 2019-01-03 17:25:46 | 270.0000 | 2019-01-03 17:25:46
start | end | diff | endtime
-------------------------------------------------------------------------
2019-01-03 17:21:03 | 2019-01-03 17:21:14 | 11.00000 | 2019-01-03 17:21:14
2019-01-03 17:21:14 | 2019-01-03 17:21:16 | 2.000000 | 2019-01-03 17:21:16
答案 0 :(得分:0)
在MySQL 8+中,您应该使用窗口函数:
SELECT lag(created) over (order by created) AS start,
created AS end,
coalesce(UNIX_TIMESTAMP(created) - UNIX_TIMESTAMP(lag(created) over (order by created)), 0) as diff
FROM events e
ORDER BY e.created;
在早期版本中,您的代码编写得不好,因为MySQL不保证SELECT
中表达式的求值顺序。