How to update the id column starting from 1 again

前端 未结 4 1318
执念已碎
执念已碎 2021-01-28 04:25

I am having problem to update the list of id number again starting from 1,2,3,4,5. Since I have deleted few records as I was testing the sql commands. Can you please help on how

4条回答
  •  [愿得一人]
    2021-01-28 05:20

    (tldr; it's usually better not to worry about the density or sequential order an auto-increment column.)

    It is not possible1 to use an AUTO_INCREMENT to automatically fill in values less than MAX(ID).

    However, the auto increment ID can be reset if existing IDs are updated. The compacting phase is required because MySQL does not allow "filling in gaps" via an auto-increment column.

    1. Compact the existing IDs, like so:

      SET @i := 0;
      UPDATE t id = @i := (@i+1)
      

      Important: Make sure that all relational usage is identified in the form of Foreign Key relations with CASCADE ON UPDATE before this is done or the data may become irreversibly corrupted.

    2. Assign the auto-ID see to the maximum1 ID value after compacting:

      ALTER TABLE t AUTO_INCREMENT = (SELECT MAX(id) FROM t)
      

    1 Per the AUTO_INCREMENT documentation in ALTER TABLE:

    You cannot reset the counter to a value less than or equal to the value that is currently in use .. 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 AUTO_INCREMENT column value plus one.

    The rule means that it is not possible to set the increment ID lower than an already used ID; in addition, manually assigning a value higher will automatically raise the AUTO_INCREMENT value.

提交回复
热议问题