仅在更新特定列时才更新日期列

时间:2019-06-28 09:02:19

标签: mysql

我仅在更新“图像”列时才需要自动更新“ time_updated”列值。如果另一列已更新,则“ time_updated”列应保持不变。

CREATE TABLE `person` (

  `image` varchar(255) DEFAULT NULL,
  `address` varchar(1000) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `time_updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

1 个答案:

答案 0 :(得分:1)

我不确定@Tim Biegeleisen为什么认为触发器不起作用,而之前触发器似乎合适

drop table if exists t;
create table t (

  `image` varchar(255) DEFAULT NULL,
  `address` varchar(1000) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `time_updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ;

drop trigger if exists t;
delimiter $$
create trigger t before update on t
for each row 
begin
    if old.image <> new.image then
        set new.time_updated = now();
    end if; 
end $$
delimiter ;

insert into t (image,address,email,time_updated) values
('aa','bb','cc','2019-01-01 01:01:01');

update t set image = 'ab' where image = 'aa';

select * from t;



+-------+---------+-------+---------------------+
| image | address | email | time_updated        |
+-------+---------+-------+---------------------+
| ab    | bb      | cc    | 2019-06-28 10:21:01 |
+-------+---------+-------+---------------------+
1 row in set (0.00 sec)
相关问题