MySQL 查询将持续时间添加到上一条记录

MySQL query add duration to previous record

我喜欢在每次添加新记录时将事件持续时间添加到以前的记录中。

这就是我的

ID EventType EventTime EventDuration
-------------------------------------
1  TypeA     10:20     NULL
2  TypeB     09:30     NULL
3  TypeC     08:00     NULL

这就是我想要实现的:

ID EventType EventTime EventDuration
-------------------------------------
1  TypeA     10:20     00:50
2  TypeB     09:30     01:30
3  TypeC     08:00     ...
4  ...       ...

添加新记录(带有 ID、EventType 和 EventTime)时,应将前一条记录的持续时间(TypeB 和 Type A 之间的时间差)添加到 EventDuration 列中的前一条记录。

我目前拥有的是:

SELECT 
   id, EventTime,
   timestampdiff(minute,
      (SELECT EventTime 
       FROM TableName t2
       WHERE t2.id < t1.id ORDER BY t2.id DESC LIMIT 1),EventTime) 
       AS EventDuration
       FROM records t1
       WHERE id = ....<this is where I get stuck, this should be a query that identifies the ID of latest EventTime record>

有什么建议吗?

(我是运行MySQL5.6.39)

如果你是 运行 MySQL 8.0,你可以使用 window 功能:

update mytable t
inner join (
    select id, timediff(eventTime, lag(eventTime) over(order by eventTime)) event_duration
    from mytable t
) t1 on t1.id = t.id
set t.event_duration = t1.event_duration

如果只想更新最后一个记录,可以在子查询(或外部查询)中order bylimit

update mytable t
inner join (
    select id, timediff(eventTime, lag(eventTime) over(order by eventTime)) event_duration
    from mytable t
    order by id desc
    limit 1, 1
) t1 on t1.id = t.id
set t.event_duration = t1.event_duration

在早期版本中,一种选择是使用 window 函数模拟 lag()

update mytable t
inner join (
    select 
        id, 
        timediff(
            (select min(eventTime) from mytable t1 where t1.eventTime > t.eventTime),
            eventTime
        ) event_duration
    from mytable t
) t1 on t1.id = t.id
set t.event_duration = t1.event_duration