19

How can I update table's column in a trigger after update on the same table?
Here's the trigger:


CREATE TRIGGER upd_total_votes AFTER UPDATE ON products_score
FOR EACH ROW
    UPDATE
        products_score 
    SET
        products_score.votes_total =
            (SELECT
                 (votes_1 + votes_2 + votes_3 + votes_4 + votes_5)
             FROM
                 products_score
             WHERE
                 id = new.id)

Now when I update the table like


UPDATE products_score SET votes_1 = 5 WHERE id = 0

this doesn't work, as I get the following:

#1442 - Can't update table 'products_score' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.

So how on earth I can get this to work?

2 Answers 2

31

If you change your trigger to BEFORE instead of AFTER you could do it like this:

CREATE TRIGGER upd_total_votes BEFORE UPDATE ON products_score 
FOR EACH ROW 
BEGIN
    SET new.votes_total = new.votes_1 + new.votes_2 + new.votes_3 + new.votes_4 + new.votes_5 
END
;
Sign up to request clarification or add additional context in comments.

Comments

8

You can't have this the way you have setup because a trigger can't query other rows of the same table that it is defined on. Istead you can use a Before Update Trigger toachieve what you want:

CREATE TRIGGER upd_total_votes BEFORE UPDATE ON products_score FOR EACH ROW     
BEGIN
    SET NEW.votes_total = NEW.votes_1 + NEW.votes_2 + NEW.votes_3 + NEW.votes_4 + NEW.votes_5;
END;

Or use a stored procedure to update the table.

1 Comment

same error message calling a stored procedure inside the trigger after update

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.