This seems to be a basic question but I can't seems to figure it out
I'v got 2 tables: table_a and table_b
SELECT * FROM `table_a`
+----+--------+----------+
| id | a_item | a_values |
+----+--------+----------+
| 1 | 1 | 5 |
| 2 | 1 | 5 |
+----+--------+----------+
SELECT * FROM `table_b`;
+--------+-------+
| a_item | total |
+--------+-------+
| 1 | 10 |
+--------+-------+
# NOTE: total is TEN
As it shows I'm using a Trigger to SUM(a_values) from table_a, and store that results in table_b.
The trigger I am using is:
CREATE TRIGGER totaling
AFTER INSERT ON table_a
FOR EACH ROW
BEGIN
INSERT INTO table_b(a_item, total)
SELECT a_item, SUM(a_values) FROM table_a
GROUP by a_item
ON DUPLICATE KEY UPDATE
total = VALUES(total);
END
Now lets say, I update table_b:
UPDATE table_b
SET total = total - 5
WHERE a_item = 1
# NOTE: I'm subtracting FIVE from previous total which was TEN
and the result on table_b total column is 5, which is expected
SELECT * FROM `table_b`
+--------+-------+
| a_item | total |
+--------+-------+
| 1 | 5 |
+--------+-------+
Up to this point, everything is working accordingly
However when I do a insert on table_a the calculations goes off.
example:
INSERT INTO table_a(a_item, a_values)
VALUES
(1, 5);
SELECT * FROM `table_b`;
+--------+-------+
| a_item | total |
+--------+-------+
| 1 | 15 |
+--------+-------+
# NOTE: see how the total has changed from FIVE to FIFTEEN, my expected result is TEN
I could fix this issue by directly updating on table_a, then the insert Trigger will only SUM with it's existing values which will give me my expected result.
the question is, is there a way where I could get the desired result without manipulating table_a, and only manipulating table_b, or do I need to change the insert Trigger ?
thanks.
I think the trigger you want is to maintain the sum in
b, not to reset it. That would be:You probably also want an
UPDATEtrigger as well.