Let's create a TestParent
table which caches the total value of the num
column in a TestChild
table, and insert some rows.
CREATE TABLE TestParent (
id INT NOT NULL PRIMARY KEY,
total INT NOT NULL DEFAULT 0);
CREATE TABLE TestChild (
parent_id INT NOT NULL,
num INT NOT NULL);
INSERT INTO TestParent (id) VALUES (123);
INSERT INTO TestChild (parent_id, num) VALUES (123, 1);
CREATE PROCEDURE Sync (IN parent INT)
UPDATE TestParent SET total = (
SELECT SUM(num) FROM TestChild WHERE parent_id=parent)
WHERE id=parent;
CALL Sync (123);
So far, so good. Now, I want Sync
to be called automatically...
CREATE TRIGGER TestInsert
AFTER INSERT ON TestChild
FOR EACH ROW CALL Sync (parent_id);
This also works. Now,
INSERT INTO TestChild (parent_id, num) VALUES (123, 1);
gives
#1054 - Unknown column 'parent_id' in 'field list'
The insert has happened, but the stored procedure hasn't been called. What's going on?
You need to use a
NEW.parent_id
to refer to a value that just got inserted