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


基础教程推荐
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 带更新的 sqlite CTE 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01