gpt4 book ai didi

mysql - 如何在记录删除后从上次停止的地方创建一个 id auto_increment?

转载 作者:可可西里 更新时间:2023-11-01 07:43:01 28 4
gpt4 key购买 nike

这没什么大不了的,但我想知道是否可以做到。现在,当我插入一条新记录时,自动增量并设置为主键的 id 字段将其值增加一个:

id | first_name | last_name
------------------------------
1 | John | Smith
2 | Jane | Doe

但是,如果我删除记录 2,我插入的下一条记录的 ID 将为 3。有什么方法可以让它的 ID 自动为 2(无需手动插入)?

最佳答案

auto_increment 计数器(至少,对于 InnoDB) 保存在表元数据中,并且独立于表中的数据:它是递增的当插入一些数据时,仅此而已。

所以,不,不可能让您的 auto_increment 列获得最大值 + 1 —— 或者至少在插入时不会。


不过,我想一个解决方案可能是更改 表,以强制auto_increment 计数器为一个新值。不确定您是否可以将它设置为比当前值更低的值,尽管(这正是您想要做的)

有关更多信息,请参阅 the manual page of alter table 上的这一段(引用,强调我的):

To change the value of the AUTO_INCREMENT counter to be used for new rows, do this:

ALTER TABLE t2 AUTO_INCREMENT = value;

You cannot reset the counter to a value less than or equal to any that have already been used.
For MyISAM, if the value is less than or equal to the maximum value currently in the AUTO_INCREMENT column, the value is reset to the current maximum plus one.
For InnoDB, if the value is less than the current maximum value in the column, no error occurs and the current sequence value is not changed.


所以,根据手册:

  • 您可以更改auto_increment的值
  • 您可以将其设置为表中列的最大值(加一?)。
    • 不过,请注意您执行此操作的方式,因为尝试对 InnoDb 使用太低的值将不会导致任何更改。


不过,请注意使用 alter table 可能不应该太频繁...

关于mysql - 如何在记录删除后从上次停止的地方创建一个 id auto_increment?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2531055/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com