mysql getting last_insert_id() in a trigger(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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:mysql 在触发器中获取 last_insert_id()


基础教程推荐
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01