[英]Inserting new values of a column in previously deleted row ID's place not after last inserted row ID
I want to assign values to a column In this manner 我想以这种方式为列分配值
1,2,3,4,5,...1000 1,2,3,4,5,... 1000
If I insert values for column 如果我为列插入值
1,2,3,4,5,6,7 1,2,3,4,5,6,7
Using auto increment Now I want to delete 2,3
And the next insertion should be 2,3,
not 8
After 2,3
is completed then my insertion should start with 8 ...
使用自动增量现在我要删除2,3
,下一个插入应该是2,3,
而不是8
完成2,3
之后,我的插入应该从8 ...
开始8 ...
AUTO_INCREMENT
behaves like this; AUTO_INCREMENT
行为是这样的; it doesn't fill the gaps arising from deleted data, it just appends the new entries to the "bottom" of the current enumeration. 它不会填补由已删除数据引起的空白,它只是将新条目追加到当前枚举的“底部”。 This is because, in a vast majority of cases, it's a very bad practice to reuse unique identifiers. 这是因为,在大多数情况下,重用唯一标识符是非常糟糕的做法。
There is pretty much nothing you can do about it... except changing the design of your table so that the identifier field doesn't have the AUTO_INCREMENT
property and, then, implementing your own logic to fill the gaps upon insertion. 除了更改表的设计以使标识符字段不具有AUTO_INCREMENT
属性,然后实施自己的逻辑以填补插入时的空白外,您几乎无能为力。 Finding the smallest unused identifier and assigning it to the upcoming insertion is pretty easy: 查找最小的未使用标识符并将其分配给即将插入的标识符非常简单:
SET @GapId = (
SELECT MIN(T1.ID + 1)
FROM MyTable T1
LEFT JOIN MyTable T2 ON T2.ID = T1.ID + 1
WHERE T2.ID IS NULL
);
INSERT INTO MyTable(ID,...) VALUES (@GapId,...);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.