0

有两个表items,并且items_history在表中发生插入后,items我希望items_history使用以下触发器将条目插入表中。

我有点困惑和担心我做得不对,我正在创建两个变量NEW.iidNEW.ip这些都是插入到调用触发器的插入上的值。我是否正确地获取了两个值并将它们插入到items_history表中,还是有更好更有效的方法来做到这一点?

iidon table 是表上items_history的 FOREIGN KEY 。iditems

DROP TRIGGER IF EXISTS `item_created_trg`;
CREATE TRIGGER `item_created_trg`
AFTER INSERT ON `items` FOR EACH ROW
BEGIN
     SET NEW.iid = (SELECT MAX(id) FROM `items` LIMIT 1);
     SET NEW.ip = (SELECT created_ip FROM `items` i WHERE i.id=NEW.iid LIMIT 1);
     INSERT INTO `items_history` (iid, title, description, created, created_by, created_ip) VALUES (NEW.iid, 'Added to database.', '', NOW(), 1, NEW.ip);
END;

提前致谢。

4

1 回答 1

1

如果我理解正确,您的触发器应该如下所示

CREATE TRIGGER item_created_trg
AFTER INSERT ON items
FOR EACH ROW
  INSERT INTO items_history (iid, title, description, created, created_by, created_ip)
  VALUES (NEW.id, 'Added to database.', '', NOW(), 1, NEW.created_ip);

这是SQLFiddle演示

于 2013-09-03T15:21:08.270 回答