在插入触发器后更新另一个 table 的列值

Update column value of another table in After Insert Trigger

我有两个不同的 table:OrderItem 和 Item。两个 table 都有一个名为“pieces”的列。在 table OrderItem 的情况下,件数是 OrderItem 列表中每个项目的数量,在 table Item 的情况下,件数表示产品的剩余件数(在例如仓库)。

所以我正在构建一个插入后触发器,它将在 OderItem

中完成插入后更新 Items 中的片段
delimiter //

create trigger TrgItemPieces
after insert on OrderItem
for each row
begin
 declare PiecesNew int;
  select a.pieces - new.Pieces into PiecesNew from Item a where a.ID = new.ItemId;
  update Item set pieces = PiecesNew where id = new.ItemId;
 end//

delimiter ;

但是当我插入时 INSERT INTO OrderItem VALUES ([OrderID],[ItemID],Pieces); 我收到以下错误:Error Code: 1442. Can't update table 'Item' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.。 我做错了什么以及如何解决?

编辑: 我通过在插入语句 INSERT INTO ORDERITEM VALUES(1,(select i.ID from Item where i.Name = 'Item1'),5);

中执行 select 来获取 ItemID

这是 MySql 避免死锁的安全措施。

但是您可以通过不直接从将通过触发器更新的 table 中进行选择来避免它。

例如使用变量。

CREATE TRIGGER TrgOrderItemAftIns
AFTER INSERT ON ORDERITEM
FOR EACH ROW
BEGIN
  INSERT INTO DEBUG_TABLE (MSG) VALUES (CONCAT('TrgOrderItemAftIns: ', NEW.ITEMID,',',NEW.PIECES));
  UPDATE ITEM SET PIECES = PIECES - NEW.PIECES WHERE ID = NEW.ITEMID;
END;
SET @OrderID = (select ID from TabOrder where Name = 'Order 1');
SET @ItemID  = (select ID from ITEM where Name = 'Item1');
INSERT INTO ORDERITEM (OrderID, ITEMID, PIECES) VALUES 
(@OrderID, @ItemID, 5);

SET @OrderID = (select ID from TabOrder where Name = 'Order 1');
SET @ItemID  = (select ID from ITEM where Name = 'Item2');
INSERT INTO ORDERITEM (OrderID, ITEMID, PIECES) VALUES 
(@OrderID, @ItemID, 1);

SET @OrderID = (select ID from TabOrder where Name = 'Order 2');
SET @ItemID  = (select ID from ITEM where Name = 'Item1');
INSERT INTO ORDERITEM (OrderID, ITEMID, PIECES) VALUES 
(@OrderID, @ItemID, 3);

演示 db<>fiddle here