MySQL Trigger不更新表

时间:2012-02-19 14:27:53

标签: php mysql triggers

我在MySQL数据库中创建了以下触发器。这是一个星级评分系统。只要在评级表中添加了一行,就应该将其添加到ratings_totals表中。

DELIMITER$$

create trigger update_vote_after_insert_trig before insert 
on ratings
for each row begin 
if bookID = new.bookID then
update ratings_totals set 
total_votes = total_votes + 1,
total_rating = total_rating + new.rating,
overall_rating = total_rating / total_votes;
where 
bookID = new.bookID;
ELSE
insert into ratings_totals set bookID = new.bookID, total_votes =  total_votes, total_rating =  total_rating, overall_rating = overall_rating;
END IF;

END$$
DELIMITER ;

我的问题是ratings_totals表未正确更新。它包含四行:bookID,total_votes,total_rating和overall_rating。只更新bookID表;其余的仍然是0.

我的目标是第一次插入行,并在此之后更新它。我这样做了吗?

2 个答案:

答案 0 :(得分:0)

如果您想在第一次插入并在第一次之后更新,您可以尝试使用“IF”语句。 如果(这是第一次) ///你的代码 其他 //你的代码

您可以使用“选择”查看您之前是否插入此行,这将是您的“IF”

答案 1 :(得分:0)

“新”不应该“老”吗?像:

DELIMITER $$  

create trigger update_vote_after_insert after insert 
on ratings
for each row begin
  update ratings_totals set 
    total_votes = total_votes + 1,
    total_rating = total_rating + old.rating,
    overall_rating = total_rating / total_votes  
  where 
    bookID = old.bookID;

end$$
DELIMITER ;