SQL triggers cause errors

2019-08-25 05:36发布

问题:

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?

回答1:

You need to use a NEW.parent_id to refer to a value that just got inserted

CREATE TRIGGER TestInsert
AFTER INSERT ON TestChild
FOR EACH ROW CALL Sync (NEW.parent_id);