My MySQL trigger doesn't work, simple syntax, not complicated

前端 未结 3 401
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 00:09

I don\'t know why my trigger isn\'t working, the query works when I use it manually, but when I want to be updated by a trigger it doesn\'t work. Can someone help me to know

相关标签:
3条回答
  • 2020-11-28 00:22

    As @e4c5 mentioned, even if your trigger could update the same table (it can't), your UPDATE would affect all rows of the table, not only the single row that is currently being updated.

    If you want a trigger that changes values in the row being updated, you can just use SET:

    CREATE TRIGGER `upd_PTS` BEFORE UPDATE ON `pos_table`
    FOR EACH ROW BEGIN
       IF (NEW.played_games <> OLD.played_games)
       THEN  
           SET NEW.PTS = NEW.won_games*2 + NEW.tie_games*1;
       END IF;
    END
    

    Also notice that you can't change values in the row that caused the trigger to run, unless you do it in a BEFORE trigger.

    0 讨论(0)
  • 2020-11-28 00:26

    This code triggers itself. Endless loop or Stack Overflow....

    0 讨论(0)
  • 2020-11-28 00:35

    A stored function or trigger cannot modify a table that is already being used (for reading or writing) by the statement that invoked the function or trigger.

    from: Stored program restrictions.

    Generally with a trigger that is fired on insert, if you want to change the value that is being inserted you make the trigger of the type BEFORE INSERT and change the values in NEW

    also noticed that the following statement isn't what you want anyway.

    update pos_table set PTS=((NEW.won_games*2)+(NEW.tie_games*1));
    

    It updates the entire table while I think you are only trying to update a sepcific row. Anyway, this is a simple calculation so you don't really need to store this column. You can just as easily calculate the value at display time and make your code a whole lot simpler + avoid the issue with the trigger.

    0 讨论(0)
提交回复
热议问题