Mysql: What should I do if the self-increasing ID is discontinuous when using on duplicate key update?

After executing the on duplicate key update statement, you will find that the database AUTO_INCREMENT will continue to grow. Even if there is no new data, AUTO_INCREMENT will continue to grow if you just modify the data, resulting in discontinuous self-increasing IDs.

Solution

Method 1 : After each execution of the on duplicate key update statement, execute the following statement to reset the auto-incremented id.

ALTER TABLE 表格名 AUTO_INCREMENT = 1;

The principle is: because self-increasing IDs are primary keys and must not be repeated, they must be unique. Therefore, after setting it to 1, mysql will automatically detect whether AUTO_INCREMENT is legal. If it is not legal, it will automatically set AUTO_INCREMENT to the current table max(id )+1

Method 2 : Modify the mysql configuration and set the innodb_autoinc_lock_mode configuration to 0

innodb_autoinc_lock_mode中有3种模式, 0、1、2, mysql默认为1,

0:每次分配自增id的时候都会锁表,这个对并发不太支持
1:只有在bulk insert的时候才会锁表,简单insert的时候只会使用一个light-weight mutex,比0的并发性能高
2:很多不保证,不太安全,不建议使用

If you change the innodb_autoinc_lock_mode value to 0 and execute INSERT... ON DUPLICATE KEY UPDATE... again, you will find that auto_increment has not increased, because this mode directly adds AUTO_INC lock and releases it when the statement is executed. You will find that there is no increase. If the number of rows is increased, the auto-incrementing ID will not be increased.
 

Method 3 : Delete the auto-incrementing primary key of the table

Delete the auto-increasing primary key and let the unique index serve as the primary key. In this way, there is basically no need to make any changes. Just make sure that the current auto-increasing primary key has no actual use. In this case, the efficiency may be affected when inserting and deleting, but if it is used for queries In most cases, it is quite cost-effective.

Method 4 : Modify business logic

Modify the business logic and separate the INSERT ... ON DUPLICATE KEY UPDATE ... statements. Query first and then update. This will ensure that the primary key will not increase uncontrollably, but it will increase the complexity. The original One request may become two. First check whether it is available, and then update it.

Guess you like

Origin blog.csdn.net/panjiapengfly/article/details/129343827