问题
I have a table with auto_incremented field.
The way normally auto increment works is it always start with the max value + 1.
For e.g. if I insert two records, auto increment field takes 1 and 2 as the value initially.
Now when I add a third row by explicitly mentioning the id field value as 100.
After this, If I add a fourth record, auto increment value will be 101, not 3.
My Question :
Is there any way in mysql to enforce auto increment to follow its series?
If it encounters a duplicate, it can skip that.
回答1:
I doubt if this can be done. Imagine this scenario: You insert 5 rows with ids 1 through 5 and delete the rows with ids 2 through 4, and end up with two rows, the one with id 1 and id 5. Now you insert another row. What id would you expect the DB to use now, 2, or 6?
I for one wouldn't want the database to do the former, because my program could rely on some primary keys not being there (think a deleted blog post with a unique id. Would you want someone to see a different blogpost when they hit the URL corresponding to that id versus just showing a 404?)
Coming back to your question, the DB doesn't really know the difference between the following two situations:
- The row with id = 100 was inserted like you mention, manually.
- There existed 100 rows with ids 1 through 100 and rows 3 through 99 were deleted.
Of course, you might have a use-case for recycling ids, but you'll have to do it yourself. But before doing that, make sure you really want it :)
来源:https://stackoverflow.com/questions/31985556/how-to-block-auto-increment-to-set-the-next-number-always-as-maxnumber-1