When the unique key (unique key and primary key) is repeated in the data table, the duplicate key error occurs.
There are three solutions to this problem: the following data structure is an example
Mysql> use test;
Mysql> create table 'user' ('userid' int (11) default null, 'username' varchar (255) not null default '');
Add the userid column primary key
Mysql> alter table 'user' add primary key 'userid' ('userid ');
Insert data
Mysql> insert into 'user' values (1, 'Eric '), (2, 'Jesus ');
Now I want to insert or edit a record with userid 1, but I don't know if it already exists.
1. Delete and insert
Mysql> delete from user where userid = 1;
Mysql> insert into user values (1, 'xxxxx ');
2. replace
Mysql> replace into user values (1, 'newvalue ');
In this case, the logic is like this. mysql first checks whether the record exists. If yes, it first deletes the record and then inserts the record independently. so you can see that affected rows is two after this statement is executed (the premise is that there is only one record of userid 1 in your data table)
3. Use insert into... on duplicate key update
Mysql> insert into user1 values (1, 'newvalueagain ') on duplicate key update user1.username = VALUES (username );
The affected rows of this statement is also 2.
Of course, another way to handle this problem is to use php directly,
Select first. If no result is found, insert; otherwise, update.
You can also update it first and find that affected rows is 0, then insert.
But obviously neither of these methods directly handed over the work to mysql for high processing efficiency