在相同 table MySQL 上更新触发器 5.6

Update Trigger on same table MySQL 5.6

我有一个包含 'featured'、'restaurant_id'、'retaurant_stock' 列的 table 'foods'。 在条件相同的 table 上更新列 'featured' 后,如何使用触发器或 mySQL 版本 5.6 上可用的任何其他解决方案更新列 'restaurant_stock'? mySQL 5.6 版不提供计算列。

这是我的触发器:

CREATE TRIGGER update_restaurant_stock BEFORE UPDATE ON foods
OR EACH ROW
BEGIN
IF NEW.featured = 1 THEN
UPDATE `foods` SET NEW.restaurant_stock = (NEW.restaurant_id);
ELSE
UPDATE `foods` SET NEW.restaurant_stock = 0;
END IF;
END

现在,当我更新列 'featured' 时,我收到以下错误消息:

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

感谢您的帮助!

您不能那样更新当前行,您可以使用 set 来更改新值

DELIMITER $$
CREATE TRIGGER update_restaurant_stock BEFORE UPDATE ON foods
OR EACH ROW
BEGIN
IF NEW.featured = 1 THEN
    SET NEW.restaurant_stock = (NEW.restaurant_id);
ELSE
    SET NEW.restaurant_stock = 0;
END IF;
END$$
DELIMITER ;
CREATE TRIGGER tr_bu_foods
BEFORE UPDATE 
ON foods
FOR EACH ROW
-- update restaurant_stock 
SET NEW.restaurant_stock = NEW.restaurant_id * (NEW.featured = 1);