MySQL trigger with conditions on UPDATE

独自空忆成欢 提交于 2020-06-18 16:01:27

问题


Is it possible to insert a conditional type of update in a mysql trigger? If I need to do something after a certain type of update, for example if the update is a certain type of changing in field value. Better said, if I need to increment a value in another table after that a specific field in my original table changes his value to a specific value, is it possible? Any help will be greatly appreciated.
I'm trying this:

CREATE TRIGGER Increment 
AFTER UPDATE ON Subscription
FOR EACH ROW
BEGIN
UPDATE USER
SET num_sub=num_sub+1
IF NEW.State <> OLD.State AND NEW.STATE='C'
END IF
END

But it doesn't work, syntax error. I insert the trigger via phpmyadmin.


回答1:


Try something like this:

CREATE TRIGGER Increment 
AFTER UPDATE ON Subscription
FOR EACH ROW
BEGIN
    IF NEW.State <> OLD.State AND NEW.STATE='C' THEN
        UPDATE USER
        SET num_sub=num_sub+1
        WHERE USER.id = NEW.user_id; -- change this condition as you need
    END IF;
END

This should also work:

CREATE TRIGGER Increment 
AFTER UPDATE ON Subscription
FOR EACH ROW
    UPDATE USER
    SET num_sub=num_sub+1
    WHERE USER.id = NEW.user_id
      AND NEW.State <> OLD.State
      AND NEW.STATE='C';

Note: NEW and OLD refer to the row from the Subscription table which is being updated. OLD contains the values before the update. NEW contains the values after the update. So to check if the state has been changed you can compare NEW.State <> OLD.State.



来源:https://stackoverflow.com/questions/46392537/mysql-trigger-with-conditions-on-update

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!