简体   繁体   English

防止在MySQL id字段中出现空白

[英]prevent gaps in MySQL id field

I have a MySQL table with an auto incremement id field. 我有一个带有自动增量ID字段的MySQL表。 When I delete a row and then insert a new row, The id of the row I deleted is skipped and the new gets an id of one greater than the previous row. 当我删除一行然后插入新行时,将删除我删除的行的ID,而新ID的ID将比上一行大1。 Is there any way I can prevent this? 有什么办法可以防止这种情况? I would like the new row to just replace the old one. 我希望新的行替换旧的行。 Is there an important reason why this happens that I am missing? 我为什么会错过这种重要原因吗?

The MySQL auto-increment function NEVER goes backward unless you force it to. 除非您强制执行,否则MySQL自动递增功能绝不会向后退。 And for a good reason. 并且有一个很好的理由。 What if there was stray references to the missing records (logs, tables, etc...)? 如果对丢失的记录(日志,表等)有零星的引用怎么办?

You can force it by using this command: 您可以使用以下命令强制执行此操作:

ALTER TABLE tbl AUTO_INCREMENT = 1000;

Or, if you need to do it as part of the query: 或者,如果您需要将其作为查询的一部分:

LOCK TABLES tbl WRITE;
SELECT @id := MAX(id) FROM tbl;
INSERT INTO tbl SET id=@id, ...;
UNLOCK TABLES;

If you are using InnoDB, you could do this in a transaction instead... 如果您使用的是InnoDB,则可以在事务中执行此操作...

Better to leave it be, however. 最好还是保留它。

The definition of an autoincrement field is that every new row inserted is guaranteed to get a unique value. 自动增量字段的定义是保证插入的每个新行都获得唯一值。 If you want to keep the old value then you must UPDATE the row instead of replacing it. 如果要保留旧值,则必须更新该行而不是替换它。 If your design requires that autoincrement column values be contiguous then you will have to manage that yourself. 如果您的设计要求自动增量列的值是连续的,那么您将必须自己进行管理。

I'm sorry but I don't know the exact reason. 抱歉,我不知道确切原因。

AFAIK you can't avoid that behavior unless you TRUNCATE the table or explicitly specify the id. 除非您对表进行TRUNCATE或明确指定ID,否则您无法避免这种行为。

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

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