我正在尝试创建一个简单的触发器,但是,如果值来自 @total <,我无法在 prato 上设置媒体值/ strong>或 @sum 。 我已经测试过将它们替换为“1”或“1 + 1”,看看我是否还没有正确更新,或者问题是操作本身。
DELIMITER $$
CREATE
TRIGGER ratings_prato BEFORE INSERT ON ratings
FOR EACH ROW BEGIN
SET @total = @total + 1;
SET @sum = NEW.stars + @sum;
UPDATE prato p SET p.media = @sum/@total WHERE p.id = 1;
END;
$$
DELIMITER ;
任何想法?
答案 0 :(得分:0)
我已完成误导触发器上的FOR EACH ROW
。我想,每次更新,它都将通过所有行。但是,而不是它,它为更新的每一行执行,这使得事情成为可能。
这是我的触发器的最后一个结果,插入评级和更新食物( prato )
DELIMITER $$
CREATE
TRIGGER inserting_dishes_rating AFTER INSERT ON ratings
FOR EACH ROW BEGIN
IF(NEW.food_id is not null) THEN
SET @media = (SELECT SUM(stars) FROM ratings WHERE food_id = NEW.food_id) / (SELECT COUNT(*) FROM ratings WHERE food_id = NEW.food_id);
UPDATE foods f SET f.rate = @media WHERE f.id = NEW.food_id;
ELSE
SET @media = (SELECT SUM(stars) FROM ratings WHERE restaurant_id = NEW.restaurant_id) / (SELECT COUNT(*) FROM ratings WHERE restaurant_id = NEW.restaurant_id);
UPDATE restaurants r SET r.rate = @media WHERE r.id = NEW.restaurant_id;
END IF;
END