mysql在触发器中获取last_insert_id() [英] mysql getting last_insert_id() in a trigger

查看:206
本文介绍了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?

我想做的基本上是这个

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?

或者触发器中可能有一些要从导致触发器触发的insert语句中获取值?我对此一无所获.

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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆