SQL触发器会导致错误

时间:2012-02-26 16:32:16

标签: mysql sql triggers mysql-error-1054

让我们创建一个TestParent表,用于缓存num表中TestChild列的总值,并插入一些行。

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);

到目前为止,这么好。现在,我希望自动调用Sync ...

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

这也有效。现在,

INSERT INTO TestChild (parent_id, num) VALUES (123, 1);

给出

#1054 - Unknown column 'parent_id' in 'field list'

插入已发生,但尚未调用存储过程。发生了什么事?

1 个答案:

答案 0 :(得分:2)

您需要使用NEW.parent_id来引用刚刚插入的值

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