问题
I have a table of web pages, with the primary key as hash of the URL, and an auto_increment ID column, which is also a unique key.
What I'm a bit confused by is why successive inserts don't increment the ID field by 1. When I first created the table and did a single insert, the first id was 1. The second insert produced and id of 5 and the third was 8.
I have a trigger on the table which, on insert, computes the hash of the URL of the webpage. Not sure if that's relevant or not.
It's not a problem to have gaps, but I would like to understand why successive inserts don't generate IDs with a step size of 1.
thanks!
回答1:
Several suggestions of why this may be happening:
See auto_increment_increment. This controls the incrementation each time a new value is requested during INSERT.
Also if you use InnoDB tables in MySQL 5.1, they optimized auto-inc allocation so that it locks the table for a shorter duration. This is good for concurrency, but it can also "lose" auto-inc values if the INSERT of a row conflicts with another constraint such as a secondary UNIQUE column or a foreign key. In those cases, the auto-inc value allocated is not pushed back into the queue, because we assume another concurrent thread may have already allocated the next auto-inc value.
Of course rollbacks also occur, in which case an auto-inc value may be allocated but discarded.
回答2:
It could be related to transactions that end up getting rolled back. For example,
- Insert google.com id=5
- Insert mysql.com id=6
- Insert stackoverflow.com id = 7
- rollback insert google.com
- rollback insert mysql.com
Then stackoverflow.com is inserted with id=7 and 5 and 6 are left blank.
回答3:
The auto increment is always with steps of 1, but once a row gets removed, the ID is not freed up.
The next auto increment ID is stored in the information schema database in your MySQL environment. It is always +1, and when a row gets removed, the ID in between will be missing. So if the first is 1, and the second (according to you) is 5, then 2,3,4 have been removed in the process.
Run this query to find out, and replace the last 2 values in the where ;)
SELECT AUTO_INCREMENT
from `information_schema`.`TABLES`
WHERE TABLE_NAME = '<<YOUR TABLE NAME HERE>>' AND
TABLE_SCHEMA = '<< YOUR DATABASE NAME HERE >>'
回答4:
mysql.cnf / ini can set the change:
auto-increment-increment = 2
auto-increment-offset = 1
In some configuration (for example, for master/master replication), a_i can skip numbers using these variables.
来源:https://stackoverflow.com/questions/8262863/how-is-the-mysql-auto-increment-step-size-determined