我正在对表执行触发操作。我想在下一个插入中插入最后一个ID的位置。因为它是一种日志管理。每当任何插入,更新或删除操作自动执行时,将激活此触发器并执行插入操作。我在这里只实现了插入操作,但没有理解我如何从第一个表中获取最后一个插入的id。这是我的代码。
CREATE TRIGGER after_auction_insert
AFTER INSERT ON auction
FOR EACH ROW
BEGIN
INSERT INTO udithdr(company_id, created_by, screen_name, action, action_date) VALUES (NEW.compid, NEW.user_id, "Auction", NEW.thought_type, NEW.created_time);
DECLARE audit_hdr_id_for_auction INT(20);
select NEW.audit_hdr_id into audit_hdr_id_for_auction;
INSERT INTO auditdtl(audit_hdr_id, col_name, old_value, new_value) VALUES (audit_hdr_id_for_auction, "title", OLD.title, NEW.title);
INSERT INTO auditdtl(audit_hdr_id, col_name, old_value, new_value) VALUES (audit_hdr_id_for_auction, "description", OLD.description, NEW.description);
END $$ DELIMITER;
因此,我想从代码中将udithdr表的主键值插入auditdtl的audit_hdr_id。
答案 0 :(得分:0)
使用LAST_INSERT_ID()
功能。
将SET audit_hdr_id_for_auction = LAST_INSERT_ID();
放在INSERT INTO udithdr ...