更新mysql中的任何字段时,时间戳会自动更新

时间:2016-01-02 10:26:13

标签: mysql sql

假设我有一个名为user的表,就像这样

╔════╦══════════╦═════════════════════╗
║ id ║   key    ║       keytime       ║
╠════╬══════════╬═════════════════════╣
║  1 ║ somekey1 ║ 2016-01-01 15:39:43 ║
║  2 ║ somekey2 ║ 2016-01-02 15:39:43 ║
╚════╩══════════╩═════════════════════╝

keytime 字段类型为TIMESTAMP,默认值为 CURRENT_TIMESTAMP

更新关键字段时如何自动更新 keytime 字段

UPDATE `user` 
SET `Key` = '2' 
WHERE `id` = 1;

2 个答案:

答案 0 :(得分:1)

使用

ALTER TABLE `user` 
   MODIFY keytime TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;

自动更新。

请参阅the doc

答案 1 :(得分:1)

您可以使用BEFORE UPDATE触发器:

CREATE TABLE `user`(id INT AUTO_INCREMENT PRIMARY KEY,
                   `key` VARCHAR(100),
                   keytime TIMESTAMP DEFAULT CURRENT_TIMESTAMP);

INSERT INTO `user`(`key`, keytime) VALUES ('key', CURRENT_TIMESTAMP - 10000);

CREATE TRIGGER user_update 
BEFORE UPDATE ON `user` 
FOR EACH ROW 
   SET NEW.keytime = CURRENT_TIMESTAMP;

UPDATE `user` 
SET `Key` = '2' 
WHERE `id` = 1;  

SqlFiddleDemo