简体   繁体   English

MySQL并发多行插入-插入ID假设

[英]MySQL concurrent multi-row inserts - Insert ID Assumption

In my application, I have a lot of foreign key dependencies, and often insert large numbers of rows. 在我的应用程序中,我有很多外键依赖项,并且经常插入大量行。 What I have done up until now is run a single insert at a time, and record the insert ID. 到目前为止,我所做的只是一次运行单个插入,并记录插入ID。 This tends to take a long time when inserting a large number of rows, even when apache and mysql are run on the same server. 即使在同一台服务器上运行apache和mysql时,插入大量行时也趋于花费很长时间。

My question is, if I were to alter my application to add a number of rows with a single INSERT, would I be able to assume the ids of each row based strictly upon the last insert id returned by the mysql connection? 我的问题是,如果我要更改应用程序以使用单个INSERT添加许多行,我是否能够严格基于mysql连接返回的最后一个插入ID来假设每一行的ID? The issue is that there is the occasional situation where more than one person will be putting large amounts of information into the database at a time. 问题是,偶尔会有多个人一次将大量信息放入数据库中的情况。

From what I have been able to determine, it seems safe to assume that when you insert 500 rows, your insert ids will range from (lastInsertID) to (lastInsertID+499), regardless of whether a query from another connection has begun or ended in the time it took to complete, but I want to be sure this is accepted as safe practice. 根据我的判断,可以安全地假设,当您插入500行时,无论来自另一个连接的查询是开始还是结束,插入ID的范围都是(lastInsertID)到(lastInsertID + 499)。完成所需的时间,但我想确定这是安全的做法。

I am primarily running InnoDB, but there is the occasional MyISAM in there as well. 我主要在运行InnoDB,但偶尔也有MyISAM。

Thanks All! 谢谢大家!

-Jer -杰尔

The mysql_insert_id and the now recommended alternative mysqli_insert_id returns the first entry id from the affected table's AUTO_INCREMENT column of the last query you've ran. mysql_insert_id和现在推荐的替代mysqli_insert_id从您运行的最后一个查询的受影响表的AUTO_INCREMENT列中返回第一个条目ID。

Mysql grouped INSERT statements are inserted iteratively from the first entry AUTO_INCREMENT index. 从第一个条目AUTO_INCREMENT索引迭代插入Mysql分组的INSERT语句。 So yes it is safe to assume that the entries inserted from a single INSERT statement are contiguous. 因此可以肯定的是,从单个INSERT语句插入的条目是连续的。

Comment from the Mysql reference "The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client. This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions. 来自Mysql参考的注释“生成的ID在服务器中基于每个连接进行维护。这意味着该函数返回给定客户端的值是为影响AUTO_INCREMENT列的最新语句生成的第一个AUTO_INCREMENT值该值,即使其他客户端生成自己的AUTO_INCREMENT值也不会受到其他客户端的影响,此行为可确保每个客户端都可以检索自己的ID,而无需担心其他客户端的活动,也无需锁定或交易。

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

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