触发:引用更新的属性

时间:2014-01-21 22:23:27

标签: mysql sql triggers sql-update

我在UPDATE上有一个触发器。

从UPDATE SQL命令未更新的表中引用属性的正确过程是什么?属性是否仍在UPDATE变量中?我想获得更新行的该属性的值。

1 个答案:

答案 0 :(得分:1)

您可以使用关键字OLDNEW在MySQL更新之前和更新之后访问列的值。

例如,如果要确定在更新期间是否实际更改了列的值,则可以执行

IF NOT OLD.column_name <=> NEW.column_name THEN
    -- do something here
END IF;

注意: <=>是MySQL中的NULL安全比较运算符

BTW: MySQL中没有UPDATED虚拟表。它来自SQL Server。

这是 SQLFiddle 演示。 请注意,即使更新影响了表中的所有记录,但log表中只记录了一条消息。这是因为最终id为2的行的值保持不变。


更新:让您的finished标志保持同步,您需要触发所有事件(插入,更新,删除)。

DELIMITER //
CREATE TRIGGER tg_ai_event
AFTER INSERT ON event
FOR EACH ROW
BEGIN
  UPDATE activity a
     SET status = (EXISTS(SELECT * 
                            FROM event 
                           WHERE activity = a.activity_id
                             AND done = 0))
   WHERE activity_id = NEW.activity;
END//

CREATE TRIGGER tg_ad_event
AFTER DELETE ON event
FOR EACH ROW
BEGIN
  UPDATE activity a
     SET status = (EXISTS(SELECT * 
                            FROM event 
                           WHERE activity = a.activity_id 
                             AND done = 0))
   WHERE activity_id = OLD.activity;
END//

CREATE TRIGGER tg_au_event
AFTER UPDATE ON event
FOR EACH ROW
BEGIN
  IF NOT OLD.activity <=> NEW.activity THEN
    -- if activity id was changed for an event then clculate finished flag
    -- for both old and new activity id
    UPDATE activity a
       SET status = (EXISTS(SELECT * 
                              FROM event 
                             WHERE activity = a.activity_id 
                               AND done = 0))
     WHERE activity_id IN(OLD.activity, NEW.activity);
  ELSE
    -- otherwise calculate finished flag only if done flag is changed 
    IF NOT OLD.done <=> NEW.done THEN
      UPDATE activity a
         SET status = (EXISTS(SELECT * 
                                FROM event 
                               WHERE activity = a.activity_id 
                                 AND done = 0))
       WHERE activity_id = NEW.activity;
    END IF;
  END IF;
END//
DELIMITER ;

这是 SQLFiddle 演示