(MySQL) 无法更新存储 function/trigger 中的 table 'PARTS',因为它已被调用此存储 function/trigger 的语句使用

(MySQL) Can't update table 'PARTS' in stored function/trigger because it is already used by statement which invoked this stored function/trigger

如果条目在 table 中,我希望更新金额,否则插入新条目。

delimiter $$
CREATE TRIGGER t 
BEFORE INSERT 
ON PARTS
for each row

BEGIN
  if exists (SELECT Part_name FROM PARTS where part_name = new.part_name) then
      UPDATE PARTS SET amount=amount+NEW.amount WHERE 
      Part_name=NEW.Part_name;
   end if;
END $$
delimiter ;

当我尝试时:

mysql> insert into PARTS(Part_name,amount,Storage_ID) values('barley',1000,1);

然后我得到这个错误:

ERROR 1442 (HY000): Can't update table 'PARTS' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.

我有什么错?有什么想法吗?

你不需要触发器。你想要 insert on duplicate key update:

insert into PARTS(Part_name, amount, Storage_ID)
    values('barley', 1000, 1)
    on duplicate key update amount = amount + values(amount);

为此,您需要 parts(part_name) 上的唯一索引或主键。或者也许在 parts(part_name, storage_id)。目前还不清楚它是如何适应的。