触发以在插入前在最后一行设置或插入时间戳

时间:2019-10-31 15:47:22

标签: mysql mariadb

我需要添加一个触发器,该触发器将设置时间戳或在插入新行之前在表的最后一行插入时间戳,而无需更改创建日期的时间戳

//我的表如下:

```` topic varchar
```` payload int
```` datecreated timestamp  current_timestamp
```` dateended timestamp no  (this needs to get up updated with the current time before a new row get's inserted in the table)
any ideeas ?

2 个答案:

答案 0 :(得分:1)

您不能在触发器中执行此操作,因为触发器无法操作对其触发的表。

典型的解决方案是为此目的创建一个存储过程,该存储过程将按顺序运行更新和插入操作(最好在同一事务中)。从您的应用程序中,您将调用存储过程,而不是运行插入查询。

但是我认为查询表时即时计算信息会更简单。如果您正在运行MySQL 8.0,则可以使用窗口功能:

select
    topic, 
    payload, 
    datecreated,
    lead(datecreated) over(order by datecreated) dateended
from mytable

在早期版本中,您可以使用相关子查询:

select
    t.topic, 
    t.payload, 
    t.datecreated,
    (select min(datecreated) from mytable t1 where t1.datecreated > t.datecreated) dateended
from mytable t

答案 1 :(得分:0)

您应始终避免冗余存储数据。无需添加其他列,您应该只计算此列:

SELECT topic, payload, datecreated as start, (SELECT datecreated FROM my_table where datecreated > start order by datecreated LIMIT 1) as end FROM my_table