问题
I'm trying to create a database file with objects and sub-objects. For example,
The first table would be of jars for storing change. Each jar entry would have a autoincrement primary ID key and data about the jar, like height, diameter or whatever.
The second table would contain the coins. Each coin would have an ID (needed?) and would also have the ID of the jar that it is contained in and it's data (like value, year, etc.).
My question is what happens to the autoincrement keys when one is deleted? Say you had 4 jars:
1 2 3 4
and you deleted number 2. Would the remaining jars be renumbered 123? or would there be a gap? If there is a gap, is it filled so the next jar created would have an ID of 2? or would the next one still be 5?
Thanks
回答1:
You can read about that in the sqlite AUTOINCREMENT docs:
The usual algorithm is to give the newly created row a ROWID that is one larger than the largest ROWID in the table prior to the insert. If the table is initially empty, then a ROWID of 1 is used. If the largest ROWID is equal to the largest possible integer (9223372036854775807) then the database engine starts picking positive candidate ROWIDs at random until it finds one that is not previously used. If no unused ROWID can be found after a reasonable number of attempts, the insert operation fails with an SQLITE_FULL error.
In short, the after inserting 4 rows, deleting the second, and then inserting another one on the end, the ids would be:
1 3 4 5
回答2:
It depends on the database implementation. For instance, MySQL inititializes the autoincrement counter at server startup and then keeps the autoincrement number in memory. So if you add 10 rows to an empty table and then delete them all the next autoincrement number would be 11 not 1.
来源:https://stackoverflow.com/questions/5198656/what-happens-to-autoincrement-primary-keys-after-delete