mysql 在触发器中获取 last_insert_id()

mysql getting last_insert_id() in a trigger(mysql 在触发器中获取 last_insert_id())
本文介绍了mysql 在触发器中获取 last_insert_id()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,当您调用 last_insert_id() 时,它通过连接进行,因此您将在调用 last_insert_id() 的同一连接中插入最后一行的 ID,对吗?

It's my understanding that when you call last_insert_id() it goes by connections, so you'll get the id of the last row inserted on the same connection where last_insert_id() is called, right?

那么如果我在AFTER INSERT"触发器中调用 last_insert_id() 会怎样?

So what if I call last_insert_id() in an 'AFTER INSERT' trigger?

我想做的基本上就是这个

What I want to do is basically this

DELIMITER $$
CREATE TRIGGER sometrigger
AFTER INSERT ON sometable
BEGIN
  INSERT INTO anothertable (id, lastup) VALUES (last_insert_id(), NOW());
END $$

'anothertable' 中的 id 与'sometable' 中的 id 相同非常重要这会起作用还是我应该创建一个存储过程而不是插入到两个表中?

It's very important that the id in 'anothertable' is the same as in 'sometable' Would this work or should I create a stored procedure instead that inserts into both tables?

或者可能在触发器中有一些可以从导致触发器触发的插入语句中获取值?我还没有找到任何相关信息.

Or possibly there is some, in the trigger, to get the values from the insert statement that caused the trigger to fire? I haven't found anything about that.

推荐答案

您应该能够使用 NEW.{id column name} 来引用最后一个插入 id(例如 NEW.id 如果自增列被称为 id.)

You should be able to use NEW.{id column name} to refer to the last insert id (so for example NEW.id if the auto increment column is called id.)

这篇关于mysql 在触发器中获取 last_insert_id()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)