让我们创建一个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'
插入已发生,但尚未调用存储过程。发生了什么事?
答案 0 :(得分:2)
您需要使用NEW.parent_id
来引用刚刚插入的值
CREATE TRIGGER TestInsert
AFTER INSERT ON TestChild
FOR EACH ROW CALL Sync (NEW.parent_id);