在第二种情况下使用mysql触发错误

时间:2014-10-16 15:54:44

标签: php mysql

嘿伙计们我是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的帮助..

2 个答案:

答案 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 ;

DEMO

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