如何在不牺牲完整性的情况下在MySQL DB表中获得最新的set 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.
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.

我使用PHP将记录组插入到MySQL DB中。每当我插入一组记录时,我想给该组一个唯一的集合ID,在DB中的每组记录中增加1。

Currently, I'm checking the latest set ID in the DB and incrementing it by 1 for each new set of records.
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?
While fairly unlikely, something like that could greatly sacrifice the integrity of the data.

目前,我正在检查DB中的最新set ID,并为每一组新记录增加1。让我害怕的事情是如果我查询数据库获取最新的设置ID,和之前我可以插入一个新记录的集合ID + 1,另一个发生在插入表因此采取集合ID我使用吗?虽然不太可能,但这样的事情可能会极大地牺牲数据的完整性。

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?

我能做些什么来阻止这样的事情发生呢?是否有办法暂时锁定DB表,以便在执行SELECT/INSERT组合之前不会发生其他插入?

2 个解决方案

#1


4  

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列的单独的表,并在该表中使用单独的插入,并使用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.

然后使用该值作为插入到原始表中的行组的组标识符。

#2


3  

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. MySQL will do the work of maintaining unique keys wholly automatically, and then you can simply refer to those keys from your existing table.

说到这里,请认真考虑使用带有AUTO_INCREMENT列的表。MySQL将完全自动地维护唯一键,然后您可以简单地从现有表中引用这些键。

智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2014/07/15/7df1bf2ed6a4817d975b3c34e03e7fe4.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告