【问题标题】:Insert Id of previous inserted id into next insert in MYSQL将前一个插入的 id 的 id 插入到 MYSQL 中的下一个插入中
【发布时间】:2018-09-08 06:49:50
【问题描述】:

我正在对表执行触发操作。我想将最后一个 ID 插入下一个插入的位置。因为它是一种日志管理。每当任何插入、更新或删除操作将自动执行时,都会激活此触发器并执行插入操作。我在这里只实现了插入操作,但不了解如何从第一个表中获取最后插入的 id。这是我的代码。

CREATE TRIGGER after_auction_insert 
AFTER INSERT ON auction 
FOR EACH ROW 

开始

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);

结束$$ 分隔符;

所以我想从代码中将 udithdr 表的主键值插入到 auditdtl 的 audit_hdr_id 中。

【问题讨论】:

  • 在 INSERT 触发器中,只能使用 NEW.col_name;没有旧行。在 DELETE 触发器中,只能使用 OLD.col_name;没有新行。在 UPDATE 触发器中,您可以使用 OLD.col_name 引用更新前的行列,使用 NEW.col_name 引用更新后的行列 - dev.mysql.com/doc/refman/5.7/en/trigger-syntax.html
  • 更新 auditdtl SET audit_hdr_id = audit_hdr_id_for_auction, col_name = "title", old_value = OLD.title, new_value = NEW.title;好的 P.Salmon 但仍然遇到插入触发器中没有旧行的相同错误。
  • 我认为你没有得到它 - 在拍卖的插入触发器上没有 OLD.title 或 OLD.description 并且将 INSERT INTO auditdtl 更改为更新不会改变它.
  • 你说得对,我做不到,但我想把它插入第二张桌子,那么你有什么想法吗?

标签: mysql triggers last-insert-id


【解决方案1】:

使用LAST_INSERT_ID() 函数。

SET audit_hdr_id_for_auction = LAST_INSERT_ID();放在INSERT INTO udithdr ...之后

【讨论】:

  • INSERT INTO udithdr(company_id, created_by, screen_name, action, action_date) 值 (NEW.compid, NEW.user_id, "Auction", NEW.thought_type, NEW.created_time) SET audit_hdr_id_for_auction = LAST_INSERT_ID() ;像这样?
  • 是的,这将为您提供最后插入的 id,这必须从名称中看出。
  • 这很完美,但现在无法插入“auditdtl”表。收到“插入触发器中没有旧行”错误。
  • 为什么您会惊讶于插页上没有 OLD?
猜你喜欢
  • 2015-02-19
  • 2011-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-17
  • 1970-01-01
相关资源
最近更新 更多