问题描述
据我所知,当您调用 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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!