2014-07-24 57 views
0

我試圖創建一個簡單的觸發器,但是,我不能設置媒體上普拉託值,如果值來自@total@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

我已完成誤導FOR EACH ROW觸發器。我想,每次更新時,它都會遍歷所有行。但是,而不是它,它執行每行是更新,這使事情成爲可能。

這是我的觸發器的最後結果,將在收視率,和更新食品(這是普拉託

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