SQL resolves primary key conflicts

Source: Internet
Author: User

Insert fails when data is inserted, assuming that the value corresponding to the primary key already exists! This is the primary key violation.
When the primary key is in conflict (duplicate key), it can be selectively processed, that is, ignored, updated, or replaced.

1. Ignore

Insert ignore into table

Keep the original record, ignoring the newly inserted record

2. Replace

Replace into table

Replace the original record, delete the original record, and then insert the new record

3. Update insert into table value("xx","xx") ON DUPLICATE KEY UPDATE

In fact, this is the original need to execute 3 SQL statements (select,insert,update), reduced to 1 statements to complete.
That

IF (SELECT * FROM where 存在) { UPDATE SET WHERE ;} else { INSERT INTO;}

Such as:

insert into Tble values (1,‘xxx‘,‘xxx‘) ON DUPLICATE KEY UPDATE status =‘drain‘;Query OK, 2 rows affected (0.00 sec)

The above statement pseudo-code indicates that the

if (select * from table where id=1) { update device set status =‘drain‘ where id=1 } else { insert into table value (1,‘xxx‘,‘xxx‘)}

Obviously, the id=1 is there, so the update operation is performed

mysql> select * from table;+-------+--------+-----------+| id| status | spec_char |+-------+--------+-----------+| 1 | drain | yangting | | 2 | dead | zhong | +-------+--------+-----------+2 rows in set (0.00 sec)

SQL resolves primary key conflicts

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.