【问题标题】:mysql: how to update automatically TimeStamp when a field has been updatedmysql:如何在字段已更新时自动更新时间戳
【发布时间】:2012-11-14 00:06:34
【问题描述】:

我有一个简单的 DB 表,其中包含很少的文章数据库字段,其中是一个包含文章最后更新时间的时间戳。

我使用“ON UPDATE CURRENT_TIMESTAMP”

问题是我只想在这条记录的某些字段发生变化时才更新,而不是全部。

即对于每篇文章,我都有一个字段给出访问者阅读文章的次数。每次网络访问后不得更新...仅当我更改标题、作者等时...

最好有一个不错的 mysql 命令...


我编写了以下代码:

CREATE TRIGGER `actu_lastupdate_date` BEFORE UPDATE ON `actuality`
 FOR EACH ROW BEGIN
    if NEW.title <> OLD.title OR NEW.chapeau = OLD.chapeau OR NEW.content = OLD.content
    then
        SET NEW.LastUpdate_date = current_timestamp;
    end if;
END

似乎即使另一个记录字段正在更改,时间戳也会更新。应该有什么不好的地方。 我会调查的

【问题讨论】:

  • 你可以试试Triggers...
  • 谢谢。现在试图了解这是如何工作的

标签: mysql timestamp sql-update


【解决方案1】:

您可以编写一个触发器来在更新时添加时间戳

delimiter |
CREATE TRIGGER actu_lastupdate_date AFTER UPDATE on actuality
FOR EACH ROW
BEGIN
    if (NEW.title <> OLD.title 
         OR NEW.chapeau <> OLD.chapeau 
         OR NEW.content <> OLD.content)
        AND (NEW.other_column = OLD.other_column 
         OR NEW.other_column2 = OLD.other_column2)
    then
        SET NEW.LastUpdate_date = current_timestamp;
    end if;
END
|
delimiter ;

【讨论】:

  • 如果我理解正确,这将在每次更新行 IF col1 or col2 or col3 do no change 时在表 your_table 的 timestamp_column 字段上设置一个新的时间戳?由于仅在某些字段已更改时才需要更新时间戳,因此我需要更改 if then 条件: if (NEW.col1OLD.col1) OR (NEW.col2OLD.col2) then SET NEW.timestamp_column = current_timestamp;
  • @ThomasP:将AFTER UPDATE 更改为BEFORE UPDATE
  • 我又更新了。逻辑是:只有在title, chapeau content中的任何一个字段被更改且other_column, othercolumn2没有任何字段被更改时才设置时间戳。
  • 听起来不错。换句话说,例如,如果字段“nb_reading”正在更改,则不应更新时间戳,因为这不是 if-then 条件的一部分?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-28
  • 2013-06-27
  • 2015-08-01
相关资源
最近更新 更多