mysql's replace into "pit"

When inserting data into a table, we often encounter such a situation: 1. First determine whether the data exists; 2. If it does not exist, insert it; 3. If it exists, update it.
 
This situation can be solved by using the replace into statement, but there is no problem, let's see
 
Here's what it looks like before the data update

In the auto table, the k field is the only index. When replace into auto (k,v) values ​​(10,11); is executed, the data becomes
 

 
 As you can see from the figure, the record with id=10 is gone, and a new record with id=23 is added, and the values ​​of k and v are exactly the values ​​we just wanted to update
 
Execute another statement replace into auto (k,v) values ​​(9,9); observe the following results
 
This time, a record with id=24 was really added, while the other records did not change.
 
Through the above operations, you can see the logic executed by replace into
1. If the PRIMARY KEY or UNIQUE index is encountered, and the new record conflicts with the old record (there is an abnormal duplicate key error), the old record will be deleted, and then the new record will be inserted.
2. If there is no conflict in the new record, insert a new record directly, the same as insert into
 
It seems normal, there will be problems with the first logic here
1. After the old record is deleted, the new record inserted only inserts those specified fields. The fields that were originally not intended to be updated are directly set to the default values, which will cause data loss.
2. If the id of the old record is associated with other tables, the new record will generate a new id after the update, resulting in the loss of this association
3. And the use of replace into will cause the self-incrementing primary key id to increase all the time, which can easily lead to insufficient id value range
In addition, if there is a master-slave relationship in the database, after the replace into operation is performed on the master machine, the AUTO_INCREMENT of the corresponding table on the slave machine will not be updated, causing the newly inserted data to be abnormal when the slave machine becomes the master machine. AUTO_INCREMENT increases to the value of the original host machine. 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326316479&siteId=291194637