mysql 在触发器中获取last_insert_id()
据我了解,当您调用last_insert_id()时,它会通过连接进行,因此您将获得在调用last_insert_id()的同一连接上插入的最后一行的id,对吧?
那么如果我在“AFTER INSERT”触发器中调用last_insert_id()会怎样呢?
我想做的基本上就是这样
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 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?
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 $
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该能够使用
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 exampleNEW.id
if the auto increment column is calledid
.)