有人帮我写了以下内容:
CREATE TRIGGER update_stats AFTER UPDATE ON user_hours FOR EACH ROW
INSERT INTO hours_statistics (user_id, opportunity_id, completed_hours) VALUES
(OLD.user_id, OLD.opportunity_id, -OLD.completed_hours),
(NEW.user_id, NEW.opportunity_id, +NEW.completed_hours)
ON DUPLICATE KEY UPDATE
completed_hours = completed_hours + VALUES(completed_hours);
但是,触发器只应运行:
UPDATE user_hours JOIN user_calendar USING (user_calendar_id, opportunity_id)
SET user_hours.completed_hours = agreed_hours,
user_hours.hours_committed = 'completed'
WHERE user_hours.hours_committed = 'accepted'
AND user_hours.completed_hours IS NULL
AND user_calendar.date_start = CURRENT_DATE();
目前,如果手动调整管理员或用户completed_hours,则更新触发器仍会运行。我想在代码中添加一些IF语句,但我的尝试都无法创建触发器。
我正在寻找类似的东西:
CREATE TRIGGER update_stats AFTER UPDATE ON user_hours FOR EACH ROW
IF hours_committed = 'completed' THEN
INSERT INTO hours_statistics (user_id, opportunity_id, completed_hours) VALUES
(OLD.user_id, OLD.opportunity_id, -OLD.completed_hours),
(NEW.user_id, NEW.opportunity_id, +NEW.completed_hours)
ON DUPLICATE KEY UPDATE
completed_hours = completed_hours + VALUES(completed_hours);
END IF
END
任何人都可以提供帮助,只是不希望Trigger运行,除非满足特定条件,烦恼我们需要的代码工作,但这会在调整查询运行之外的几天内出现问题。
提前感谢。
标记
答案 0 :(得分:2)
触发器将始终运行,您需要将该条件添加到触发器的主体,并比较新更新的列(new.column
):
DELIMITER //
CREATE TRIGGER update_stats AFTER UPDATE ON user_hours
FOR EACH ROW
BEGIN
IF NEW.hours_committed = 'completed' THEN
INSERT INTO hours_statistics (user_id, opportunity_id, completed_hours) VALUES
(OLD.user_id, OLD.opportunity_id, -OLD.completed_hours),
(NEW.user_id, NEW.opportunity_id, +NEW.completed_hours)
ON DUPLICATE KEY UPDATE
completed_hours = completed_hours + VALUES(completed_hours);
END IF;
END//