Insert... On duplicate key update/replace into multi-row data Introduction

Source: Internet
Author: User

The scenario is as follows: I have a KV table. The table creation statement is as follows:

Copy codeThe Code is as follows:
Create table 'dkv '(
'K1 'int (11) not null default '0 ',
'K2' int (11) not null default '0 ',
'Val 'varchar (30) default null,
Primary key ('k1 ', 'k2 ')
) ENGINE = InnoDB default charset = utf8

The data is probably like this:

+ ---- + ----------- +
| K1 | k2 | val |
+ ---- + ----------- +
| 1 | 1 | value 1-1 |
| 1 | 2 | value 1-1 |
| 1 | 3 | value 1-1 |
| 1 | 5 | value 1-1 |
| 1 | 7 | value 1-1 |
+ ---- + ----------- +

When I insert a piece of data, I want to determine whether (k1, k2) already exists (one selete). If so, update and insert will occur. This is a typical merge process, although the operation based on PK is very fast, after all, the SQL Interaction Volume goes up. If I have 100 such SQL statements, this overhead is very considerable, is there anything that SQL can do?

There are two writing methods:

First: insert... On duplicate key update

Copy codeThe Code is as follows:
Insert DELAYED into dkv
Values
(1, 2, 'new 12a '),
(1, 3, 'new 33ba '),
(23222, 'new 1234568 '),
(12333, 'new 123456 '),
(, 'New vaaaa '),
(, 'New vaff '),
(25, 'new vaff ')
On duplicate key update val = VALUES (val );

Replace:

Copy codeThe Code is as follows:
Replace into dkv
Values
(1, 2, 'new 12a '),
(1, 3, 'new 33ba '),
(23222, 'new 1234568 '),
(12333, 'new 123456 '),
(, 'New vaaaa '),
(, 'New vaff '),
(25, 'new vaff ');

Eventually, the data can be changed to the following:

Copy codeThe Code is as follows:
+ ---- + ----------- +
| K1 | k2 | val |
+ ---- + ----------- +
| 1 | 1 | value 1-1 |
| 1 | 2 | new 12a |
| 1 | 3 | new 33ba |
| 1 | 4 | new 23222 |
| 1 | 5 | value 1-1 |
| 1 | 6 | new 12333 |
| 1 | 7 | value 1-1 |
| 1 | 8 | new vaaaa |
| 1 | 20 | new vaff |
| 1 | 25 | new vaff |
+ ---- + ----------- +

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.