简体   繁体   English

MySQL插入-对于每一行,返回插入ID

[英]MySQL insert - for each row, return insert id

Let's say I have an array of data to insert. 假设我要插入一个数据数组。 I'm going to have an insert that looks like this: 我将要插入一个如下所示的内容:

INSERT INTO `table` (`name`, `value`) VALUES('name1','value1'),('name2','value2')

We're assuming that table has a primary key. 我们假设该table具有主键。

Is there a way to, while batch inserting like this, grab the last insert id for each row, and return the those new ids? 有没有办法像这样批量插入时,获取每行的最后一个插入ID,然后返回这些新ID? I know you can't do this traditionally with LAST_INSERT_ID() , but I'm wondering if I could use something like a cursor to achieve this functionality, and maybe a temporary table to store the values until I return them. 我知道您传统上无法使用LAST_INSERT_ID()完成此操作,但我想知道是否可以使用类似游标的功能来实现此功能,还可以使用临时表来存储值,直到返回它们。

Any help would be great. 任何帮助都会很棒。

https://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html https://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html

LAST_INSERT_ID() will return the first id from a multi row insert.

So you can just return that value and: 因此,您只需返回该值即可:

INSERT INTO `table1` (`name`, `value`) VALUES('name1','value1'),('name2','value2');

SET @firstid := LAST_INSERT_ID();
SELECT * from table1 where id>=@firstid;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM