从一个表到另一个表的mysql复制值给我错误

时间:2014-10-30 02:12:42

标签: mysql triggers

我试图在表1插入数据之前使用触发器将table2中的值复制到table1,我遇到的问题是每当我向table1插入一个新行时,我都会收到一条错误消息,说明该列可以不是,在我的情况下,列是颜色。 只是fyi表1有一个名为'color'的列以及表2

这是我的代码

CREATE 
TRIGGER `some_trigger` BEFORE INSERT ON `table1`
FOR EACH ROW BEGIN
SET new.color = 
(
    SELECT table2.color
    FROM table1
    JOIN table2 ON table1.aforeignkeycolumn = table2.aprimarykeycolumn
    WHERE table1.id = new.id  --this should be the new row
);
END;

如果我有这个它会工作,但我需要获得将要插入表1的行的ID

CREATE 
TRIGGER `some_trigger` BEFORE INSERT ON `table1`
FOR EACH ROW BEGIN
SET new.color = 
(
    SELECT table2.color
    FROM table1
    JOIN table2 ON table1.aforeignkeycolumn = table2.aprimarykeycolumn
    WHERE table1.id = 10
);
END;

感谢任何帮助

1 个答案:

答案 0 :(得分:0)

插入触发后执行怎么样?

CREATE  TRIGGER `some_trigger` AFTER INSERT ON `table1`
FOR EACH ROW BEGIN
    SELECT new.color := table2.color
    FROM table1 JOIN
         table2
          ON table1.aforeignkeycolumn = table2.aprimarykeycolumn
    WHERE table1.id = new.id  --this should be the new row
END;