简体   繁体   English

Mysql 插入 ... select,获取最后插入 ID

[英]Mysql Insert … select, obtain last insert ID

I have this query in php.我在 php 中有这个查询。 It's an insert select copying from table2, but I need to get the IDs of the newly created rows and store them into an array.这是从 table2 复制的插入 select,但我需要获取新创建的行的 ID 并将它们存储到数组中。 Here is my code:这是我的代码:

$sql = "INSERT INTO table1 SELECT distinct * from table2";  
$db->query($sql);

I could revert the flow starting with a select on table2 and making all single inserts but it would slow down the script on a big table.我可以从 table2 上的 select 开始恢复流程并进行所有单次插入,但它会减慢大表上的脚本。 Ideas?想法?

You could lock the table, insert the rows, and get the ID of the last item inserted, and then unlock;您可以锁定表,插入行,并获取最后插入的项目的ID,然后解锁; that way you know that the IDs will be contiguous as no other concurrent user could have changed them.这样您就知道 ID 将是连续的,因为没有其他并发用户可以更改它们。 Locking and unlocking is something you want to use with caution though.不过,锁定和解锁是您要谨慎使用的东西。

An alternative approach could be to use one of the columns in the table - either an 'updated' datetime column, or an insert-id column (for which you put in a value that will be the same across all of your rows.)另一种方法是使用表中的一个列 - 一个“更新的”日期时间列或一个插入 ID 列(为此,您输入的值在所有行中都相同。)
That way you can do a subsequent SELECT of the IDs back out of the database matching either the updated time or your chosen insert ID.这样,您可以执行后续的 SELECT 从数据库中返回匹配更新时间或您选择的插入 ID 的 ID。

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

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