MySQL INSERT INTO ... On DUPLICATE KEY Update usage

Source: Internet
Author: User
Tags mysql insert

MySQL has been supporting inserts since version 4.1 ... On DUPLICATE KEY UPDATE syntax, which requires 3 SQL statements (select,insert,update) to be executed, and reduced to 1 statements to complete.

For example, the Ipstats table structure is as follows:

The code is as follows Copy Code
CREATE TABLE Ipstats (
IP VARCHAR not NULL UNIQUE,
Clicks SMALLINT (5) UNSIGNED not NULL DEFAULT ' 0 '
);

3 SQL statements would have been executed, as follows:

The code is as follows Copy Code
IF (SELECT * from ipstats WHERE ip= ' 192.168.0.1 ') {
UPDATE ipstats SET clicks=clicks+1 WHERE ip= ' 192.168.0.1 ';
} else {
INSERT into Ipstats (IP, clicks) VALUES (' 192.168.0.1 ', 1);
}

And now you can do this with just 1 SQL statements:

The code is as follows Copy Code
INSERT into Ipstats VALUES (' 192.168.0.1 ', 1) on DUPLICATE KEY UPDATE clicks=clicks+1;

Note that to use this statement, the condition is that the table must have a unique index or primary key.

Summarized as follows:

1. If a primary key record does not exist in the table, replace and insert*update are the same characteristics as insert.
2. If a primary key record exists in the table, replace is equivalent to performing a delete and insert two operation, whereas insert*update is equivalent to executing the IF exist do update else does insert. Therefore, if the replace fill has incomplete fields, the field that is not updated will be modified to the default value, and if there is an ID, the ID will change to the most recent value (so that the record may be lost if it is marked with a self ID); insert* Update only updates some of the fields and does not change for fields that are not updated (the default values are not enforced).

More than one record operation:

  code is as follows copy code
insert into t (a , b,c) VALUES (' A1 ', ' B1 ', ' C1 '), (' A2 ', ' B2 ', ' C2 ')
on duplicate key update t.c=values (T.C)

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.