MySQL触发器:子行中的UPDATE父行AFTER DELETE

时间:2017-06-05 16:06:15

标签: mysql triggers

当删除子行时,我需要更新父表的值。

父表:答案

  • id_answer
  • 答案
  • 投票(包含总票数)

儿童表: answers_votes

  • id_vote
  • id_answer
  • id_user
  • date_insert
  • IP

每次删除子行时,父表中投票的值必须减少1。

这是我当前创建触发器的句子,但UPDATE行有问题,也许是 votes-1 ?任何帮助将不胜感激。谢谢!

CREATE TRIGGER update_votes BEFORE DELETE on answers_votes
FOR EACH ROW
BEGIN
UPDATE answers SET answers.votes = (answers.votes-1) WHERE answers.id_answer = OLD.id_answer;
END

有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:1)

所以,我怀疑;是问题所在。我已将$$添加为DELIMITER,以便mysql客户端不会误解;

您修改的触发器将是:

DELIMITER $$
CREATE TRIGGER update_votes
BEFORE DELETE ON answers_votes
FOR EACH ROW 
BEGIN 
  UPDATE answers SET answers.votes = (answers.votes -1 ) WHERE answers.id_answer = OLD.id_answer;
END$$ 
DELIMITER ;

注意,DELIMITER ;不是DELIMITER;

希望这有帮助!