2014-01-21 101 views
0

我在UPDATE上有一個觸發器。觸發器:引用更新的屬性

從UPDATE SQL命令未更新的表中引用屬性的正確過程是什麼?該屬性是否仍然在UPDATE變量中?我想爲更新的行獲取該屬性的值。

+0

你在當前狀態下的問題是非常不清楚。你能詳細說明你想要達到的目標嗎? – peterm

+0

您的意思是:在列A更新時(對於每個更新的行),獲取列B的值? – bd33

+0

@ bd33我知道我可以使用UPDATED.attribute_name訪問更新的屬性。但是如果該屬性在查詢中沒有更新呢?我想知道更新行的該屬性的值。謝謝! – user2703038

回答

1

通過使用關鍵字OLDNEW,可以在更新之前和更新MySQL之後訪問列的值。

例如,如果你想確定是否列的值實際上已經改變時更新,你可以做

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

注:<=>是NULL安全的比較操作在MySQL

BTW: MySQL中沒有UPDATED虛擬表。它來自SQL Server。

這裏是一個SQLFiddle演示。 請注意,儘管更新會影響表中的所有記錄,但log表中只記錄了一條消息。這是因爲最終id爲2的行的價值保持不變。


UPDATE:,讓您的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演示

+0

謝謝,你能告訴我爲什麼我在MySQL中遇到這個錯誤: 以下查詢失敗了:「CREATE DEFINER ='administ' @'localhost' TRIGGER'on_event_update' AFTER UPDATE ON'event' FOR EACH ROW IF NOT(SELECT * FROM event WHERE event.activity = OLD.activity AND event.done = 0)THEN UPDATE activity SET activity.status = 0 WHERE activity.activity_id = OLD.activity END IF;「 MySQL說:#1064 - 你的SQL語法有錯誤;檢查與您的MySQL服務器版本對應的手冊,在第3行'END IF'附近使用正確的語法 – user2703038

+0

這是因爲您沒有使用'BEGIN ... END'塊,您應該這樣做,因爲您的觸發器的主體包含多於一個聲明。 – peterm

+0

如果你解釋一下你想用觸發器強制執行的邏輯,我可以幫你解決這個問題。 – peterm