Reorder / reset auto increment primary key

后端 未结 15 1726
北荒
北荒 2020-11-22 04:39

I have a MySQL table with an auto increment primary key. I deleted some rows in the middle of the table. Now I have, for example, something like this in the ID column: 12, 1

15条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 05:27

    I had the same doubts, but could not make any changes on the table, I decided doing the following having seen my ID did not exceed the maximum number setted in the variable @count:

    SET @count = 40000000;
    UPDATE `users` SET `users`.`id` = @count:= @count + 1;
    
    SET @count = 0;
    UPDATE `users` SET `users`.`id` = @count:= @count + 1;
    
    ALTER TABLE `users` AUTO_INCREMENT = 1;
    

    The solution takes, but it's safe and it was necessary because my table owned foreign keys with data in another table.

提交回复
热议问题