如何更新触发器中的多个表和字段?

时间:2013-08-29 23:55:01

标签: mysql sql triggers

我有以下架构:SQL Fiddle

触发器正在更新articles.votes字段。我还需要它来更新members.points字段和成员lifetime_points字段,使用与更新articles.votes字段相同的公式。我该怎么做?

1 个答案:

答案 0 :(得分:1)

你在找这个吗?

DELIMITER $$
CREATE TRIGGER tg_ai_article_votes
AFTER INSERT ON article_votes
FOR EACH ROW 
BEGIN
  UPDATE articles
     SET votes = COALESCE(votes, 0) + 1
   WHERE id = NEW.article_id;
  UPDATE members
     SET points = COALESCE(points, 0) + 1,
         lifetime_points = COALESCE(lifetime_points, 0) + 1
   WHERE id = NEW.member_id;
END$$

CREATE TRIGGER tg_ad_article_votes
AFTER DELETE ON article_votes
FOR EACH ROW 
BEGIN
  UPDATE articles
     SET votes = COALESCE(votes, 0) - 1
   WHERE id = OLD.article_id;
  UPDATE members
     SET points = COALESCE(points, 0) - 1,
         lifetime_points = COALESCE(lifetime_points, 0) - 1
   WHERE id = OLD.member_id;
END$$
DELIMITER ;

这是 SQLFiddle 演示