是否可以让一个时间戳列在更新一列时更新?

时间:2013-07-23 16:32:09

标签: mysql ruby-on-rails

有一个问题,是否可以在更新一列时(仅该列)更新的时间戳列?

提前多多感谢!

2 个答案:

答案 0 :(得分:5)

您可以使用trigger

DELIMITER ;;

CREATE TRIGGER foo BEFORE UPDATE ON my_table FOR EACH ROW
  IF        NEW.colA <=> OLD.colA  -- has not been updated
    AND     NEW.colB <=> OLD.colB  -- has not been updated
    AND NOT NEW.colC <=> OLD.colC  -- has been updated
    -- etc.
  THEN
    SET NEW.colD = NOW();  -- update timestamp
  END IF
;;

DELIMITER ;

请注意,您的TIMESTAMP列未启用automatic updating

答案 1 :(得分:1)

不确定。您可以将timestamp列定义为日期时间,然后在满足条件时使用触发器更新它。

粗略的语法是:

CREATE TRIGGER trigger_name AFTER UPDATE ON table FOR EACH ROW
BEGIN
  IF(
     NOT NEW.watched_column <=> OLD.watched_column AND
     NEW.other_a <=> NEW.other_a AND
     ...
    )
  THEN
     SET NEW.timestamp_column = NOW();
  END IF;
END