MYSQL 两个日期时间之间的差异

MYSQL difference between two datetime

我有以下 table.

table1:

id_user | action |  time 
--------+--------+----------------------
1       | 2      | '2009-05-18 11:45:42'
1       | 2      | '2009-05-18 11:45:45'
1       | 3      | '2009-05-18 11:45:50'
1       | 2      | '2009-05-18 11:46:50'

我想获得结果,其中列 timediff 包含与前一行的时间差(以秒为单位)。

table2

id_user | action | timediff
--------+--------+----------
1       | 2      | 3
1       | 2      | 5
1       | 3      | 60

我试过这个查询,但没有用:

SELECT
    id_user,action, 
    TIMESTAMPDIFF(SECOND,LEAD(time),time) OVER (PARTITION BY id_user, ORDER BY time) AS timediff
FROM table1

... 但它会引发错误。 :/

我阅读了其他答案,但没有看到同时使用 LEADLAGTIMESTAMPDIFF 的答案。

提前致谢。

你的语法错误,你必须使用这个:

SELECT id_user,
       action, 
       TIMESTAMPDIFF(
         SECOND, 
         time, 
         LEAD(time) OVER (PARTITION BY id_user ORDER BY time)
       )  AS timediff 
FROM table1

TIMESTAMPDIFF() 函数的第 2 个和第 3 个参数是日期时间表达式,第 2 个是从第 3 个参数中减去的。

参见demo
结果:

| id_user | action | timediff |
| ------- | ------ | -------- |
| 1       | 2      | 3        |
| 1       | 2      | 5        |
| 1       | 3      | 60       |
| 1       | 2      |          |