问题
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