Mysql Insert Or Update Syntax example

Source: Internet
Author: User
Tags mysql insert

Sometimes you will need to write an insert SQL, or update if the primary key exists, or insert if the primary key does not exist. This usage is provided in MySQL: ON DUPLICATE KEY UPDATE . Let's see how it's used!

First the original data for the database is as follows:

a   b   c1   b1  c12   b2  c23   b3  c3

This will cause an error if you execute the following SQL

INSERT INTO test VALUES(1,‘b4‘,‘c4‘);

Error message as follows, prompt cannot be inserted repeatedly:

1 queries executed, 0 success, 1 errors, 0 warnings查询:insert into test values(1,‘b4‘,‘c4‘)错误代码: 1062Duplicate entry ‘1‘ for key ‘PRIMARY‘执行耗时 : 0 sec传送时间 : 0 sec总耗时 : 0.008 sec

At this point, you can use ON DUPLICATE KEY UPDATE it, which means that the previous insert is executed first, and if the primary key is repeated, the subsequent update

INSERT INTO test VALUES (1,‘b4‘,‘c4‘) ON DUPLICATE KEY UPDATE b=VALUES(b),c=VALUES(c);

The above SQL can be simply understood as:

select count(1) from test where a=1;if count(1) > 0UPDATE test SET b=‘xxx‘,c=‘xxx‘ WHERE a=1;

After execution, you can see that there are two lines of the impact (as to why two lines are affected, you have to study the underlying implementation, you can refer to the official documentation):

1 queries executed, 1 success, 0 errors, 0 warnings查询:INSERT INTO test VALUES (1,‘b4‘,‘c4‘) ON DUPLICATE KEY UPDATE b=VALUES(b),c=VALUES(c)共 2 行受到影响执行耗时 : 0.023 sec传送时间 : 0 sec总耗时 : 0.023 sec

After execution, the data becomes the following:

a   b   c1   b4  c42   b2  c23   b3  c3

Mysql Insert Or Update Syntax example

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.