我无法在mysql中使用触发器更新表

时间:2019-01-12 17:54:34

标签: mysql sql

更新该表后,我试图填充表中的空白字段,但出现此错误:

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

我该如何解决?

我的触发器的查询:

DELIMITER $$
Create trigger OfferSum 
after UPDATE
on Services_Offer
FOR EACH ROW
BEGIN
    UPDATE Services_Offer
    SET NEW.final_price = 
    (SELECT service_price from Services_Level
    where Services_Level.level_code= Services_Offer.level_code)*Services_Offer.service_size;

END$$

2 个答案:

答案 0 :(得分:0)

我认为您需要在之前更新触发器:

DELIMITER $$

CREATE TRIGGER OfferSum BEFORE UPDATE ON Services_Offer
FOR EACH ROW
BEGIN
    SELECT NEW.final_price := sl.service_price * NEW.service_size
    FROM Services_Level sl
    WHERE sl.level_code = NEW.level_code;
END$$

答案 1 :(得分:0)

为什么您需要为此触发?看起来上面的查询将导致无限循环。每次更新一行时,它都会调用一个更新触发器,该触发器实际上会更新表,从而一次又一次地触发该触发器,直到崩溃。

相反,为什么不与初始更新一起计算和更新列。查询如下所示:

UPDATE Services_Offer 
SET 
    column1 = value1, 
    column2 = value2, 
    final_price = 
      ( 
        SELECT service_price 
        FROM Services_Level 
        WHERE Services_Level.level_code = Services_Offer.level_code
      ) * service_size
WHERE id = XXX

其中column1 = value1,column2 = value2来自您的初始更新查询。