Reputation: 767
suppose i have a table called user like this
╔════╦══════════╦═════════════════════╗
║ id ║ key ║ keytime ║
╠════╬══════════╬═════════════════════╣
║ 1 ║ somekey1 ║ 2016-01-01 15:39:43 ║
║ 2 ║ somekey2 ║ 2016-01-02 15:39:43 ║
╚════╩══════════╩═════════════════════╝
the keytime field type is TIMESTAMP and default value is CURRENT_TIMESTAMP
How to update keytime field automatically when I update key field
UPDATE `user`
SET `Key` = '2'
WHERE `id` = 1;
Upvotes: 1
Views: 37
Reputation: 204924
Use
ALTER TABLE `user`
MODIFY keytime TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
to make it update automatically.
See the doc
Upvotes: 1
Reputation: 176284
You could use BEFORE UPDATE
trigger:
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;
Upvotes: 1