MySQL“更新时间戳”列 - 触发器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2045745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MySQL 'Update Timestamp' Column - Trigger
提问by maxhugen
I'm adding a column tsu
(timestamp update) of type DATETIME
to a number of my tables.
我正在向我的许多表中添加一个tsu
类型的列(时间戳更新)DATETIME
。
I need to write BEFORE UPDATE
triggers that will update the column to CURRENT_TIMESTAMP()
, but I can't get it right. Tried:
我需要编写BEFORE UPDATE
将列更新为 的触发器CURRENT_TIMESTAMP()
,但我做对了。尝试:
DELIMITER $$
CREATE
TRIGGER `cams`.`tsu_update_csi` BEFORE UPDATE
ON `cams`.`csi`
FOR EACH ROW BEGIN
UPDATE csi SET tsu = CURRENT_TIMESTAMP WHERE csi_code = OLD.csi_code;
END$$
DELIMITER ;
Can anyone point me in the right direction pls? MTIA
任何人都可以指出我正确的方向吗?MTIA
回答by Calvin Allen
Okay, try this one:
好的,试试这个:
DELIMITER $$ CREATE
TRIGGER `cams`.`tsu_update_csi` BEFORE UPDATE
ON `cams`.`csi`
FOR EACH ROW BEGIN
SET NEW.tsu = CURRENT_TIMESTAMP;
END$$ DELIMITER ;
回答by Calvin Allen
If the field can be defined as a timestamp, you can use the following:
如果该字段可以定义为时间戳,则可以使用以下内容:
ts2 TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP);
ts2 TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP);
回答by Ian Clelland
Don't know if it'll work for you, but you can always make it a TIMESTAMP
field with no default value -- MySQL will automatically set the value of the first such field defined in the table to the current timestamp on every update.
不知道它是否适合您,但您始终可以将其设置TIMESTAMP
为没有默认值的字段——MySQL 会在每次更新时自动将表中定义的第一个此类字段的值设置为当前时间戳。