MariaDB - 更新后的复杂触发器查询

时间:2016-11-29 06:30:59

标签: mysql triggers mariadb

我有三张桌子(餐馆 - 投票 - 评论)。我想创建一个触发器,让我更新餐馆中的两个字段( restaurant_rate_average,restaurant_comment_count )。这是我的触发器:

DELIMITER $$

CREATE
    TRIGGER `change comment status` AFTER UPDATE ON `comments` 
    FOR EACH ROW
    BEGIN

       UPDATE restaurants
       INNER JOIN votes ON restaurants.restaurant_id = votes.vote_foreign_key
       SET restaurants.restaurant_comment_count = SELECT (COUNT(votes.vote_id))
       WHERE votes.vote_model = 'restaurant'
       AND WHERE old.comment_status<>NEW.comment_status;

       UPDATE restaurants
       INNER JOIN votes ON restaurants.restaurant_id = votes.vote_foreign_key
       SET restaurants.restaurant_rate_average = SELECT (AVG(votes.vote_num))
       WHERE votes.vote_model = 'restaurant'
       AND WHERE old.comment_status<>NEW.comment_status;
    END;
$$

DELIMITER ;

其实我有一个错误:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT (COUNT(votes.vote_id))
       WHERE votes.vote_model = 'restaurant'
      ' at line 8

我试图减少肤色,用2替换SELECT(COUNT(votes.vote_id)),我得到新的错误:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE comments.comment_status<>NEW.comment_status;

       UPDATE resta' at line 9

如何解决?

已编辑:

这是我的伪表:

餐馆: restaurant_id,restaurant_comment_count(int),restaurant_rate_average(int)

注释: comment_id,comment_status(boolean),comment_content(varchar),votes_vote_id(id)

票: vote_id,vote_foreign_key(id),vote_model(varchar)

已编辑2:

我创建了一个新的简单触发器,只需加入三个表,它就像魅力一样:

BEGIN
   UPDATE restaurants res
   INNER JOIN votes v ON v.vote_foreign_key = res.restaurant_id AND v.vote_foreign_key = 'restaurant'
   INNER JOIN comments cm ON cm.votes_vote_id = v.vote_id
   SET res.restaurant_rate_average = 2
   WHERE cm.comment_status = NEW.comment_status;
END

但如果我用 SELECT AVG(v.vote_id)替换 SET res.restaurant_rate_average = 2 ,我收到了一个错误。我还编辑了最后一个触发器:

BEGIN
   DECLARE RESTAURANT_RATE_AVERAGE INTEGER;
   SET RESTAURANT_RATE_AVERAGE := (SELECT AVG(votes.vote_num)
   UPDATE restaurants res
   INNER JOIN votes v ON v.vote_foreign_key = res.restaurant_id AND v.vote_foreign_key = 'restaurant'
   INNER JOIN comments cm ON cm.votes_vote_id = v.vote_id
   SET restaurant_rate_average = RESTAURANT_RATE_AVERAGE
   WHERE cm.comment_status = NEW.comment_status;
END

我在第4行收到错误。我想要的是用SELECT AVG(votes.vote_num)

替换静态数字

1 个答案:

答案 0 :(得分:-1)

changeForm