Troubleshooting a Non-Functional MySQL Trigger for Updating PTS on Game Statistics
Consider this issue: despite the manual execution of the query succeeding, a trigger intended to automatically update the PTS column based on changed played_games values is not functioning. The trigger syntax is straightforward:
<code class="sql">CREATE TRIGGER `upd_PTS` AFTER UPDATE ON `pos_table` FOR EACH ROW BEGIN IF (NEW.played_games <> OLD.played_games) THEN update pos_table set PTS=((NEW.won_games*2)+(NEW.tie_games*1)); END IF; END</code>
However, further investigation reveals an error when attempting to modify played_games manually: "Can't update table pos_table in stored function/trigger because it's already used by statement which invoked this stored function/trigger."
Explanation:
This error stems from the constraints imposed by stored functions and triggers. They are prohibited from altering tables that the invoking statement has already read from or written to.
Solution:
For triggers triggered on insert operations, if you intend to modify the values being inserted, employ a BEFORE INSERT trigger and adjust the NEW values.
Additionally, the update statement written in the trigger:
<code class="sql">update pos_table set PTS=((NEW.won_games*2)+(NEW.tie_games*1));</code>
is flawed. It updates the entire table rather than a single row. For this scenario, it's more efficient to calculate PTS at display time instead of having a dedicated column. This eliminates the need for a trigger and overcomes the trigger-related issue.
The above is the detailed content of Why Is My MySQL Trigger Failing to Update the PTS Column After Manual Execution Succeeds?. For more information, please follow other related articles on the PHP Chinese website!