使用单个触发器更新多个表

时间:2014-11-23 10:58:30

标签: mysql sql database phpmyadmin

我在使用一个触发器更新2个表时遇到问题,它在" New.userid"

附近给了我一个错误
CREATE TRIGGER userDownloads AFTER INSERT ON Downloads
FOR EACH ROW
UPDATE Project SET PROJECT_DOWNLOADS = PROJECT_DOWNLOADS + 1 WHERE PROJECTID = NEW.ProjectID,
UPDATE User SET NO_OF_DOWNLOADS = NO_OF_DOWNLOADS + 1 WHERE USERID = NEW.UserID;

1 个答案:

答案 0 :(得分:1)

您必须以这种方式编写触发器:

DELIMITER //
CREATE TRIGGER userDownloads AFTER INSERT ON Downloads
FOR EACH ROW
BEGIN
  UPDATE Project SET PROJECT_DOWNLOADS = PROJECT_DOWNLOADS + 1 WHERE PROJECTID = NEW.ProjectID;
  UPDATE User SET NO_OF_DOWNLOADS = NO_OF_DOWNLOADS + 1 WHERE USERID = NEW.UserID;
END//

请查看它有效here

但你确定需要一个触发器吗?为什么不在下载表中执行COUNT?

SELECT ProjectID, COUNT(*) AS PROJECT_DOWNLOADS
FROM Downloads
GROUP BY ProjectID;

SELECT UserID, COUNT(*) AS NO_OF_DOWNLOADS
FROM Downloads
GROUP BY UserID;