【问题标题】:MySQL trigger update row after insert where [closed]MySQL在插入后触发更新行[关闭]
【发布时间】:2013-03-21 17:29:13
【问题描述】:

我有 2 张桌子,RatingsRecipes

插入Ratings 后,我需要找到已评级食谱的所有评级的平均值,并更新Recipes 表中的Rating_Avg 列。

这可行,但我相信它会更新 Recipes.Rating_Avg 中的所有行,而我只需要更新 Recipe_No = 最近评级的 Recipe_No 的行。

CREATE TRIGGER `update_avg` AFTER INSERT ON `Ratings`
 FOR EACH ROW UPDATE Recipes
SET Rating_Avg = (SELECT AVG(Rating) from Ratings where Ratings.Recipe_No=Recipes.Recipe_No)

我觉得我需要添加一个WHERE Recipe_No = NEW.Recipe_No,但我不确定在哪里添加它。

【问题讨论】:

    标签: mysql triggers sql-update


    【解决方案1】:

    每次触发触发器时,您确实在更新食谱中的所有行。使用 NEW.Recipe_No 伪列,您可以将更新限制为仅受影响的食谱记录:

    CREATE TRIGGER update_avg AFTER INSERT ON `Ratings`
    FOR EACH ROW UPDATE Recipes
      SET Rating_Avg = (SELECT AVG(Rating) from Ratings where Ratings.Recipe_No=Recipes.Recipe_No)
    WHERE Recipes.Recipe_No=NEW.Recipe_No
    

    【讨论】:

    • 谢谢,我想我是在正确的轨道上哈哈
    猜你喜欢
    • 2016-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多