简体   繁体   English

MySQL多行插入是否会获取顺序自动增量ID?

[英]Does a MySQL multi-row insert grab sequential autoincrement IDs?

I think this is true, but I haven't found anything on the web to confirm it. 我认为这是事实,但我没有在网上找到任何确认信息。 I can get the first id generated for the autoincrement field using last_insert_id(), but can I assume that the next records will have sequential IDs? 我可以使用last_insert_id()获取为自动增量字段生成的第一个id,但是我可以假设下一个记录将具有顺序ID吗? Or could another user grab an id so that the resulting IDs are not sequential? 或者其他用户是否可以获取ID,以便生成的ID不是连续的?

Example: insert into mytable (asdf, qwer) values (1,2), (3,4), (5,6), ... , (10000,10001); 示例:插入mytable(asdf,qwer)值(1,2),(3,4),(5,6),...,(10000,10001);

If mytable has an autoincrement column, and if two users run this statement at the same time, will one user grab 10000 sequential IDs, and the other user the next 10000 sequential IDs? 如果mytable有一个自动增量列,并且如果两个用户同时运行此语句,一个用户将获取10000个连续ID,而另一个用户将获得下一个10000个连续ID吗? How about for hundreds of users? 数百名用户怎么样?

Thanks. 谢谢。

It depends on the storage engine used. 这取决于使用的存储引擎。

  • MyISAM guarantees the inserted rows to have sequential ID's, since a table-level lock is held during the insert. MyISAM保证插入的行具有顺序ID,因为在插入期间保持表级锁定。
  • InnoDB : unless innodb_autoinc_lock_mode is set to interleaved (2) , the inserted rows will have sequential ID's. InnoDB :除非innodb_autoinc_lock_mode设置为interleaved(2) ,否则插入的行将具有顺序ID。 By default InnoDB runs in consecutive mode since 5.1 and traditional mode prior. 默认情况下,InnoDB在5.1和traditional模式之前以consecutive模式运行。

For more on the innodb_autoinc_lock_mode option, see 13.6.4.3. 有关innodb_autoinc_lock_mode选项的更多信息,请参见13.6.4.3。 AUTO_INCREMENT Handling in InnoDB AUTO_INCREMENT在InnoDB中处理

If you use LOCK TABLES, the batches should grab sequential id's. 如果您使用LOCK TABLES,批次应该获取顺序ID。

Example: 例:

LOCK TABLES users WRITE;
<BULK INSERT HERE>
UNLOCK TABLES;

This will prevent multiple threads from writing to the table at the same time. 这将防止多个线程同时写入表。

A multi-row insert is just a bulk-operation that performs the same operation over and over again. 多行插入只是一个批量操作,一遍又一遍地执行相同的操作。 When an insert statement is fired, it fires a trigger that generates the ID. 触发insert语句时,它会触发生成ID的触发器。

So if the database engine used, performs all of its work in a sequential way (queue like - first-in first-out) then yes, sequential id's will be one increment higher than the previous id; 因此,如果使用数据库引擎,则以顺序方式执行其所有工作(队列类似 - 先进先出)然后是,顺序id将比前一个id高一个增量; if the data is inserted in a multi-threaded way where statements are fired in parallel, then no, id's will be given at "random". 如果以并行方式触发语句的多线程方式插入数据,则不会在“随机”中给出id。

I am not aware of any mysql engine that guarantees this, but then again I haven't made much research in this specific subject. 我不知道有任何mysql引擎可以保证这一点,但是我再也没有对这个特定的主题进行过多的研究。

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

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