Mysql insert/update usage

Source: Internet
Author: User
Tags mysql insert

Some insert/update operations of mysql may use the following statements when inserting data using conditions in MySQL. Create a simple table for testing:

CREATE TABLE `books` (  `id` INT(11) NOT NULL AUTO_INCREMENT,  `name` VARCHAR(200) NOT NULL,  PRIMARY KEY (`id`),  UNIQUE KEY `NewIndex1` (`name`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

1. insert ignore into: when data is inserted, if an error occurs, such as duplicate data, no error is returned and only returned as a warning. Therefore, use ignore to ensure that the statement is correct, otherwise it will be ignored. For example:
INSERT IGNORE INTO books (name) VALUES ('MySQL Manual')

 

2. on duplicate key update when primary or unique is repeated, the update statement is executed. For example, if it is a useless statement after update, for example, id = id, the function is the same as 1, however, errors are not ignored. For example, to insert duplicate name data without an error, you can use the following statement:
INSERT INTO books (name) VALUES ('MySQL Manual') ON duplicate KEY UPDATE id = id

 

3. insert... Select... Where not exist determines whether to insert data based on the select condition. It can be determined not only by primary and unique, but also by other conditions. For example:
INSERT INTO books (name) SELECT 'MySQL Manual' FROM dual WHERE NOT EXISTS (SELECT id FROM books WHERE id = 1)

 

4. replace into: If a record with the same primary or unique exists, delete it first. Insert a new record.
REPLACE INTO books SELECT 1, 'MySQL Manual' FROM books

 


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.