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

眉间皱痕 提交于 2020-07-30 09:06:50

问题


I'm really bad at SQL, but I'm trying to keep my database simple and minimalistic as possible. Not duplicating values but using references and id's instead.

Now after inserting a query I get error

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

Query can be inserted when the trigger is disabled. But my query is only reading from table 'users' so there should not be a conflict. I read something about deadlock - the query is locking table while using it or something like that and therefore a trigger cannot update a row? Ideas how could I achieve this?

I simplified my query so only important things are there.

Query:

INSERT INTO signed (time_of_start, player)
    SELECT time_of_game_id, users.user_id 
    FROM time_of_game, users
    WHERE time_of_game.time_of_start = "2017-02-01 12:00:00"
      AND users.steamid = "1234567890123456";

Trigger:

CREATE TRIGGER `payment_for_joining` 
AFTER INSERT ON `signed`
FOR EACH ROW 
    UPDATE users  
    SET users.credit = users.credit-1
    WHERE users.user_id = NEW.player

回答1:


It won't allow you to update the table because it's already being read by the INSERT INTO.. SELECT query that invokes this trigger.

An alternative way would be to disable the trigger and update the users table separately, e.g.:

INSERT INTO signed (time_of_start, player)
SELECT time_of_game_id, users.user_id FROM time_of_game, users
WHERE time_of_game.time_of_start="2017-02-01 12:00:00"
AND users.steamid="1234567890123456";

UPDATE users join time_of_game SET users.credit = users.credit-1
where time_of_game.time_of_start="2017-02-01 12:00:00"
AND users.steamid="1234567890123456";

You can add a join column with ON clause if there is any column that links these two tables.



来源:https://stackoverflow.com/questions/41537750/1442-cant-update-table-in-stored-function-trigger-because-it-is-already

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