Mysql Tutorial: Considerations for ON DUPLICATE KEY UPDATE

Source: Internet
Author: User

MySQL versions later than MySQL 4.1 Support INSERT... The on duplicate key update syntax allows you to execute three SQL statements (SELECT, INSERT, UPDATE) and reduce them to one statement.

For example, the ipstats table structure is as follows:

Reference

Create table ipstats (
Ip VARCHAR (15) not null unique,
Clicks SMALLINT (5) unsigned not null default '0'
);

Originally, three SQL statements were required:

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 );
}

Now, you only need to run the following SQL statement:

Insert into ipstats VALUES ('192. 168.0.1 ', 1) on duplicate key update clicks = clicks + 1;

Note: To use this statement, the table must have a unique index or primary key.

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.