The interviewer asks: MySQL auto-incrementing ID run out, what will happen?

Here Insert Picture Description

Since this knowledge is not clear, then go back on the next hands-on experience.
First, create a simple table contains only an auto-incremented id, and insert a piece of data.

 `create table t0(id int unsigned auto_increment primary key) ;`
 `insert into t0 values(null);`

By show command show create table t0; see Table situation
``
CREATE TABLEt0 (
the above mentioned id int(10) unsigned NOT NULL AUTO_INCREMENT,
PRIMARY KEY (the above mentioned id)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8

Can be found AUTO_INCREMENT has been automatically becomes 2, which is still very far from exhausted, we can calculate the maximum current ID increment statement is the largest number since this definition is intunsigned, it can be up to 32 power of two --1 = 4294967295

Here is a tip, when you can create a table directly declared initial value of AUTO_INCREMENT

create table t1(id int unsigned auto_increment primary key) auto_increment = 4294967295;
insert into t1 values(null);

Similarly, the show command to view the table structure of t1

 `CREATE TABLE `t1` (`
`  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,`
`  PRIMARY KEY (`id`)`
`) ENGINE=InnoDB AUTO_INCREMENT=4294967295 DEFAULT CHARSET=utf8`

Can be found, it has become the AUTO_INCREMENT 4294967295, and when one would like to try to insert data obtained following abnormal results

17:28:03    insert into t1 values(null) Error Code: 1062. Duplicate entry '4294967295' for key 'PRIMARY'    0.00054 sec

Description, when inserted again, or use the increment ID 4294967295 reported primary key violation error.

4294967295. This number can already meet most of the scenes, and if your services are frequent insert and delete data, then run the risk still exists, recommended bigint unsigned, this number is big.

However, there is an alternative, if you create a table in a primary key does not show stated, how would you do?

If this is the case, InnoDB will automatically help you create an invisible, a length of 6 bytes row_id, and InnoDB maintains a global dictsys.row_id, so no primary key of the table is shared by row_id, each insert a data, regarded as a global row_id primary key id, then add a global row_id

The global row_id use in the implementation of the code is bigint unsigned types, but in fact only 6 bytes to row_id left, this design will there is a problem: If the global row_id been rising, has been up 48 times until a power of 2 -1, this time to + 1, row_id lower 48 is 0, the result in a new row of data is inserted, to get row_id is 0, there is a possibility of conflict of the primary key.

Therefore, to avoid this risk, each table would need a given primary key.

Published 90 original articles · won praise 7 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_20282955/article/details/104232167