Someone has helped me write the following:
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);
However, the trigger should only run for:
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();
As it stands currently, if admin or user completed_hours are manually adjusted, the update trigger still runs. I would like to add some IF statement to the code but my attempts all failed to create the trigger.
I’m looking for something like:
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
Anyone able to help, just dont want the Trigger running unless specific condition is met, annoying that the code works we need but this makes a problem for days outside of the adjustment query being ran.
thanks in advance.
Mark
The trigger will always run, you need to add that condition to the body of the trigger, and compare the newly updated column (
new.column):