我正在尝试在mysql中设置触发器。 实际上我正在尝试将最后插入的记录从notes表插入到log_trigger中,但是下面的代码不能正常工作。
DELIMITER $$
CREATE TRIGGER `after_note`
AFTER INSERT ON `notes`
FOR EACH ROW
BEGIN
INSERT INTO log_trigger (NoteId, customerContact, customer, users, note, NoteCreatedTs)
SELECT Id, customerContact, customer, users, note, CreatedBy FROM notes ORDER BY id DESC LIMIT 1
END$$
DELIMITER ;
请建议
答案 0 :(得分:2)
您无需使用select
从使用触发器的同一表中选择最后一个数据。您可以使用new
关键字。
delimiter //
create trigger after_note after insert on notes
for each row
begin
insert into log_trigger
(NoteId, customerContact, customer, users, note, NoteCreatedTs)
values
(new.id,new.customerContact,new.customer,new.users,new.note,new.CreatedBy);
end;//
delimiter ;
答案 1 :(得分:1)
不是引用实际notes表中的物理行,而是引用New
伪行(它将匹配被触发的基础表的列定义):
INSERT INTO log_trigger (NoteId, customerContact, customer, users, note, NoteCreatedTs)
SELECT New.PostId, New.customerContact, New.customer, New.users, New.note, New.CreatedBy;
New
已经包含新插入的行 - 您不需要再次找到它。