When my users_reputation points table gets updated (insert), I want to take a new count (SUM) of this user's points and update a total_rep column in the users table.
This is what I came up with but keep getting syntax errors. I would greatly appreciate if somebody could point out my mistakes.
CREATE TRIGGER after_insert_rep_points AFTER INSERT ON users_reputation
FOR EACH ROW
BEGIN
DECLARE new_total INT(10);
SELECT SUM(rep_points) INTO new_total FROM users_reputation
WHERE user_id = NEW.user_id;
UPDATE users SET rep_total = new_total WHERE user_id = NEW.user_id;
END
These are my table examples for reference:
USERS:
user_id | first_name | total_rep
-------------+----------------+--------------
10001 | Jim | 17
10002 | Bob | 5
USERS_REPUTATION:
user_id | rep_task | rep_points | rep_date
-----------+-------------------------------+--------------+-----------------------
10001 | Commented on article | 5 | 2012-11-12 08:40:32
10001 | Read an article | 2 | 2012-06-12 12:32:01
10001 | Shared an article | 10 | 2012-06-04 17:39:44
10001 | Read an article | 2 | 2012-05-19 01:04:11
10002 | Commented on article | 5 | 2012-06-17 09:34:21