What should I do if the self-increasing ID of MySQL is used up?

Since this point of knowledge is not clear, then go back and practice it yourself.

First, create a simplest table that contains only an incrementing id and insert a piece of data.

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

Through the show command show create table t0; view the table

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

It can be found that AUTO_INCREMENT has automatically become 2, which is still far from running out. We can calculate the maximum value of the largest currently declared self-increment ID. Since the definition here is intunsigned, the maximum can reach 2 to the power of 32. -1 = 4294967295

Here is a little trick, you can directly declare the initial value of AUTO_INCREMENT when creating the table

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

Similarly, through the show command, 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

It can be found that AUTO_INCREMENT has become 4294967295. When I try to insert a piece of data, I get the following abnormal result

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

It shows that when it is inserted again, the auto-increment ID used is still 4294967295, and the error of primary key conflict is reported.

4294967295, this number can already cope with most scenarios, if your service will frequently insert and delete data, there is still a risk of running out, it is recommended to use bigint unsigned, this number will be large.

However, there is another situation. What if the declared primary key is not displayed in the created table?

If this is the case, InnoDB will automatically help you create an invisible row_id with a length of 6 bytes, and InnoDB maintains a global dictsys.row_id, so tables with undefined primary keys all share the row_id, and each insert A piece of data, the global row_id as the primary key id, and then the global row_id plus 1

The global row_id uses the bigint unsigned type in the code implementation, but in fact only 6 bytes are reserved for row_id, this design will have a problem: if the global row_id has been rising, it has been rising until 2 to the power of 48 At -1, and then +1 at this time, the lower 48 bits of row_id are all 0. As a result, when a new row of data is inserted, the row_id obtained is 0, and there is a possibility of primary key conflict.

Therefore, in order to avoid this hidden danger, each table needs to set a primary key.

Guess you like

Origin www.cnblogs.com/CQqfjy/p/12724123.html