当你从数据库mysql中删除一条记录时
我对整个数据库场景很陌生,只是在学习。我有一个数据库 mysql,我正在使用 phpmyadmin 来编辑字段等。我创建了一个 auto_incremenet 'id' 字段,该字段设置为主要字段。如果我添加 5 个字段,则 id 将为“1,2,3,4,5”。如果我删除所有这些字段并添加另外 5 个字段,为什么 ID 会变为“6,7,8,9,10”? (而不是回到 0,因为技术上其他字段不再存在,所以它是唯一的,对吧?)。有没有办法让id按顺序排列? 1,2,3,4,5?
i'm new to the whole database scenario and just learning. I have a database mysql and i am using phpmyadmin to edit fields etc. I created a auto_incremenet 'id' field that is set as a primary. If i add 5 fields, the id will be '1,2,3,4,5'. If i delete all those fields and add another 5 fields, why does the ID go to '6,7,8,9,10'? (instead of going back to 0, since technically the other fields do not exist anymore so its unique right?). Is there a way to make the id be sequentially numeric? 1,2,3,4,5 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你不需要担心它。您的主键应该是一个无符号整数,它可以容纳足够大的数字。
You don't need to worry about it. Your primary key should be an unsigned int which can hold large enough numbers.
我相信发生这种情况是因为在使用关系数据库系统时,您可以将行“链接”到其他行,通常是通过它们的 ID。如果您开始重复使用 ID,那么您最终可能会陷入混乱的境地。
您可以使用以下查询将 auto_increment 计数器重置为您希望的值:
如果您要删除表中的所有行,则可以使用 TRUNCATE,这也会重置计数器。
I believe this happens because when using a relational database system, you can "link" rows to other rows, usually by their id. If you start reusing IDs, then you might end up in confusing situations.
You can reset the auto_increment counter to whatever you wish using the following query:
If you are deleting all rows in your table, you can use TRUNCATE which will also reset the counter.
我认为这种行为的主要原因是效率,这意味着MySQL不需要跟踪哪些数字没有被使用,它只需要知道最后使用的是哪个数字。
I think the main reason for this behaviour is efficiency, it means that MySQL doesn't need to track which numbers are not used, it only need to know which number was last used.
看看这个问题。但基本上:
更新
如前所述,摆弄自动生成的 PK 会无限期地给您带来很多麻烦。或者编写一堆样板代码来进行内务管理。
Have a look at this question. But basically:
UPDATE
As mentioned, fiddling with auto generated PKs will indefinitely cause you a lot of headache. Or writing a bunch of boilerplate code to do housekeeping.
您必须重置自动增量,以便可以对 auto_incremented 值重新编号,在此处阅读有关解决方案的更多信息 http://www.dbuggr.com/milly/reset-auto-increment-mysql/。
You will have to reset the auto increment, so you can renumber the auto_incremented values, read more about the solutions here http://www.dbuggr.com/milly/reset-auto-increment-mysql/.