我是MySQL新手。我有两个表total_loaner和available_loaner。我正在尝试为total_loaner中添加的每个新行创建一个触发器,我想将该新行添加到available_loaner。
这里的表格如下:
CREATE TABLE `total_loaner` (
`Kind` varchar(10) NOT NULL,
`Type` varchar(10) NOT NULL,
`Sno` varchar(10) NOT NULL,
PRIMARY KEY (`Sno`)
)
CREATE TABLE `available_loaner` (
`Kind` varchar(10) NOT NULL,
`Type` varchar(10) NOT NULL,
`Sno` varchar(10) NOT NULL,
`Status` char(10) NOT NULL DEFAULT '',
PRIMARY KEY (`Sno`)
)
我的触发器似乎不起作用。
CREATE TRIGGER new_loaner_added
AFTER INSERT ON 'total_loaner' for each row
begin
INSERT INTO available_loaner (Kind, Type, Sno, Status)
Values (new.Kind, new.Type, new.Sno, 'Available');
END;
答案 0 :(得分:14)
在你的情况下,你可以像这样重写你的触发器
CREATE TRIGGER new_loaner_added
AFTER INSERT ON total_loaner
FOR EACH ROW
INSERT INTO available_loaner (Kind, Type, Sno, Status)
VALUES (NEW.Kind, NEW.Type, NEW.Sno, 'Available');
注意:强>
total_loaner
中删除单引号,因为引号有效地使其成为字符串文字而不是正确的标识符。如果你愿意,你可以使用后退,但这是不必要的,因为它不是保留字,也不包含任何特殊字符。 DELIMITER
命令和BEGIN...END
阻止这是 SQLFiddle 演示
答案 1 :(得分:6)
您可能需要设置分隔符:
DELIMITER $$
CREATE TRIGGER new_loaner_added
AFTER INSERT ON `total_loaner` for each row
begin
INSERT INTO available_loaner (Kind, Type, Sno, Status)
Values (new.Kind, new.Type, new.Sno, 'Available');
END$$
DELIMITER ;
现在,它使INSERT
语句末尾的分号与CREATE TRIGGER
语句的结尾混淆。
答案 2 :(得分:4)
这个为我工作,更简化的版本..
CREATE TRIGGER new_loaner_added
AFTER INSERT ON `DB1`.`table_name`
FOR EACH ROW
INSERT INTO `DB2`.`table_name` (messageID, conversationID, fromJID)
VALUES (NEW.messageID,NEW.conversationID, NEW.fromJID);
答案 3 :(得分:0)
AFTER INSERT ON `total_loaner`
使用反引号。
答案 4 :(得分:-1)
CREATE TRIGGER new_loaner_added
AFTER INSERT ON total_loaner
FOR EACH ROW
INSERT INTO available_loaner (Kind, Type, Sno, Status)
VALUES (NEW.Kind, NEW.Type, NEW.Sno, 'Available');