简体   繁体   English

如何在不牺牲完整性的情况下在MySQL数据库表中获取最新的设置ID?

[英]How do I get the latest set ID in a MySQL DB table without sacrificing integrity?

I'm using PHP to insert groups of records into a MySQL DB. 我正在使用PHP将记录组插入MySQL数据库。
Whenever I insert a group of records, I want to give that group a unique set ID that is incremented by 1 for each group of records in the DB. 每当我插入一组记录时,我想给该组一个唯一的集ID,对于DB中的每组记录,该ID增加1。

Currently, I'm checking the latest set ID in the DB and incrementing it by 1 for each new set of records. 目前,我正在检查数据库中的最新设置ID,并为每个新记录集将其递增1。
The thing that scares me though is what happens if I query the DB to get the latest set ID, and before I can insert a new set of records with that set ID + 1, another insert occurs on the table thus taking the set ID I was about to use? 令我害怕的是,如果我查询数据库以获取最新的设置ID,并且在我可以插入具有该设置ID + 1的新记录集之前发生的事情,则在表上发生另一个插入,从而获取设置ID I即将使用?
While fairly unlikely, something like that could greatly sacrifice the integrity of the data. 虽然不太可能,但类似的东西可能会大大牺牲数据的完整性。

What can I do to prevent such a thing from happening? 我该怎么做才能防止这种事情发生? Is there any way to temporarily lock the DB table so that no other inserts can occur until I have performed a SELECT/INSERT combo? 有没有办法临时锁定数据库表,以便在我执行SELECT / INSERT组合之前不会发生其他插入?

Locking the table is one option, but that approach impacts concurrency. 锁定表是一种选择,但这种方法会影响并发性。

The approach I would recommend is that you use a separate table with AUTO_INCREMENT column, and use a separate INSERT into that table, and a SELECT LAST_INSERT_ID() to retrieve the auto_increment value. 我建议的方法是使用带有AUTO_INCREMENT列的单独表,并在该表中使用单独的INSERT,并使用SELECT LAST_INSERT_ID()来检索auto_increment值。

And then use that value as the group identifier for the group of rows you insert into your original table. 然后使用该值作为插入原始表的行组的组标识符。

The basic approach is: 基本方法是:

LOCK TABLE foo WRITE;
SELECT MAX(id) + 1 FROM foo
INSERT ...
INSERT ...
UNLOCK TABLES;

Locking the table prevents any other process from changing the table until you explicitly unlock it. 锁定表会阻止任何其他进程更改表,直到您明确解锁它为止。

Having said that, seriously consider just using a table with an AUTO_INCREMENT column. 话虽如此,认真考虑只使用带有AUTO_INCREMENT列的表。 MySQL will do the work of maintaining unique keys wholly automatically, and then you can simply refer to those keys from your existing table. MySQL将完全自动地维护唯一键,然后您可以简单地从现有表中引用这些键。

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

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