How to deal with repeated primary keys in mysql

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.