How to fill in the “holes” in auto-increment fields?

后端 未结 7 917
时光说笑
时光说笑 2020-11-27 06:12

I\'ve read some posts about this but none cover this issue.

I guess its not possible, but I\'ll ask anyway.

I have a table with more than 50.000 registers. I

7条回答
  •  被撕碎了的回忆
    2020-11-27 06:46

    You generally don't need to care about gaps. If you're getting to the end of the datatype for the ID it should be relatively easy to ALTER the table to upgrade to the next biggest int type.

    If you absolutely must start filling gaps, here's a query to return the lowest available ID (hopefully not too slowly):

    SELECT MIN(table0.id)+1 AS newid
    FROM table AS table0
    LEFT JOIN table AS table1 ON table1.id=table0.id+1
    WHERE table1.id IS NULL
    

    (remember to use a transaction and/or catch duplicate key inserts if you need concurrent inserts to work.)

提交回复
热议问题