如何将许多行插入MySQL表并返回新ID?

Pea*_*oon 70 mysql bulkinsert

通常我可以在MySQL表中插入一行然后last_insert_id返回.但是,现在,我想在表中批量插入许多行并返回一组ID.有谁知道我怎么做到这一点?

有一些类似的问题,但它们并不完全相同.我不想将新ID插入任何临时表; 我只是想取回ID数组.

我可以从批量插入中检索lastInsertId吗?

带有last_insert_id()的Mysql mulitple row insert-select语句

Dag*_*sen 64

旧线程,但只是调查了这一点,所以这里说:如果您在最新版本的MySQL上使用InnoDB,您可以使用LAST_INSERT_ID()和获取ID列表ROW_COUNT().

当进行批量插入时,InnoDB保证AUTO INCREMENT的序号,前提innodb_autoinc_lock_mode是设置为0(传统)或1(连续).因此,您可以通过添加来获取第一个 ID LAST_INSERT_ID()最后一个 ID ROW_COUNT()-1.

  • 你需要交易吗?如果其他插入物出现在中间怎么办? (5认同)
  • 只要您使用InnoDB引擎并确保启用了auto_increment锁定(这可能会导致性能降低),就不需要显式的事务定义.由于InnoDB在插入期间执行锁定,因此其他插入必须等待插入完成.看看http://dev.mysql.com/doc/refman/5.1/en/innodb-auto-increment-handling.html (3认同)

Kev*_*ton 16

我认为可以做到的唯一方法是,如果为插入的每组行(guid)存储唯一标识符,然后选择行ID.例如:

INSERT INTO t1
(SELECT col1,col2,col3,'3aee88e2-a981-1027-a396-84f02afe7c70' FROM a_very_large_table);
COMMIT;

SELECT id FROM t1 
WHERE guid='3aee88e2-a981-1027-a396-84f02afe7c70';
Run Code Online (Sandbox Code Playgroud)

您还可以使用在数据库中生成guid uuid()


小智 5

假设我们有一个名为 temptable 的表,有两个列 uid,col1,其中 uid 是一个自动递增字段。执行如下操作将返回结果集中所有插入的 id。您可以循环遍历结果集并获取您的 id。我意识到这是一篇旧文章,这个解决方案可能并不适用于所有情况。但对于其他人来说可能是这样,这就是我回复它的原因。

# lock the table
lock tables temptable write;

#bulk insert the rows;
insert into temptable(col1) values(1),(2),(3),(4);

#get the value of first inserted row. when bulk inserting last_insert_id() #should give the value of first inserted row from bulk op.
set @first_id = last_insert_id();

#now select the auto increment field whose value is greater than equal to #the first row. Remember since you have write lock on that table other #sessions can't write to it. This resultset should have all the inserted #id's
select uid from temptable where uid >=@first_id;

#now that you are done don't forget to unlock the table.
unlock tables;
Run Code Online (Sandbox Code Playgroud)