嘿伙计们我是mysql的新手。我已经用mysql触发器做了一些代码,但它在第二个条件下抛出了我的错误。 代码
create table foo (a INT, b INT, ts TIMESTAMP);
create table bar (a INT, b INT);
INSERT INTO foo (a,b) VALUES(5,1);
INSERT INTO foo (a,b) VALUES(4,2);
INSERT INTO foo (a,b) VALUES(3,3);
CREATE TRIGGER ins_sum AFTER UPDATE ON foo
FOR EACH ROW
insert into bar values(OLD.a,NEW.b);
UPDATE foo SET a = 3 WHERE b = 1;
成功输出5
。
create table foo (a INT, b INT, ts TIMESTAMP);
create table bar (a INT, b INT);
INSERT INTO foo (a,b) VALUES(5,1);
INSERT INTO foo (a,b) VALUES(4,2);
INSERT INTO foo (a,b) VALUES(3,3);
CREATE TRIGGER ins_sum AFTER UPDATE ON foo
FOR EACH ROW
insert into bar values(OLD.a,NEW.b);
insert into bar values(OLD.a,NEW.b);
UPDATE foo SET a = 3 WHERE b = 1;
当我打电话给select a from bar where b = 1
时。预期结果为5 and 4
。
但不是它.it输出像Schema Creation Failed: Unknown column 'OLD.a' in 'field list':
所以我的问题是为什么第二个选项在这里不起作用..我不能第二次在插入语句中添加NEW.a and NEW.b
。
Thanx的帮助..
答案 0 :(得分:0)
您需要DELIMITER
命令,以便分号不会结束触发器定义。您还需要一个BEGIN ... END
块来将多个命令放入FOR EACH ROW
循环
DELIMITER //
CREATE TRIGGER ins_sum AFTER UPDATE ON foo
FOR EACH ROW
BEGIN
insert into bar values(OLD.a,NEW.b);
insert into bar values(OLD.a,NEW.b);
END
//
DELIMITER ;
答案 1 :(得分:0)
问题在于此部分:
CREATE TRIGGER ins_sum AFTER UPDATE ON foo
FOR EACH ROW
insert into bar values(OLD.a,NEW.b);
insert into bar values(OLD.a,NEW.b);
是两个语句。您有两个分号,因此MySQL将其解析为两个命令。第一个命令是:
CREATE TRIGGER ins_sum AFTER UPDATE ON foo
FOR EACH ROW
insert into bar values(OLD.a,NEW.b);
第二个是:
insert into bar values(OLD.a,NEW.b);
第二个命令无效。
因为您正在插入multiple times into the same table,所以您可以尝试这样的事情:
CREATE TRIGGER ins_sum AFTER UPDATE ON foo
FOR EACH ROW
insert into bar values (OLD.a, NEW.b), (OLD.a, NEW.b);