Change mysql auto increment id column value

浪尽此生 提交于 2021-01-07 03:52:23

问题


I have a mysql table with an gpid AUTO_INCREMENT NOT NULL UNIQUE column.

After filling this table (which has 50M+ entries), I have realized that mysql still increments AUTO_INCREMENT columns if transaction fails because of an IntegrityError, and understandably so.

The results are gaps in AUTO_INCREMENT columns, with gpid jumping values (for exemple from gpid == 3 to gpid == 5 between two consecutive rows). While this is not an issue for machines, it is one for my coworkers and I. The purpose of this column was, among other things, to represent the exact number of rows in the table.

Is there a way to change all gpid column values to a nice range (from 1 to 53926669), respecting the order the rows were inserted in the table, without having to drop/refill the table? Refilling would take me a long time.

Thank you.


回答1:


MySQL, just like other databases, does not guarantee the absence of gaps in auto-increment column. Renumbering the table may fix the issue at a particular point in time, but gaps may (and most likely) will appear in the future.

If you want a monotically increasing sequence, then auto-increment is not what you need. Instead, you can for example create a view, and use row_number():

create view myview as
select t.*, row_number() over(order by gpid) as new_gpid
from mytable t


来源:https://stackoverflow.com/questions/64930233/change-mysql-auto-increment-id-column-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!