MySQL Insert Insert Condition judgment: insert if not present

Source: Internet
Author: User
Tags bulk insert mysql insert

Absrtact: We often need to make a bulk insert of SQL, which requires that the record does not exist and is inserted, and the presence is not inserted. What if an INSERT statement is used?

Normal Insert into insert:

INSERT INTO card(cardno, cardnum) VALUES(‘1111‘, ‘100‘);INSERT INTO card(cardno, cardnum) VALUES(‘2222‘, ‘200‘);...

For normal insert inserts, if you want to ensure that no duplicate records are inserted, we only have to create a unique constraint implementation for a field (for example, the Cardno card number cannot be duplicated);

Is there a scenario that does not create a unique constraint, only through the INSERT into statement?

Answer: Yes, the specific syntax for INSERT into IF EXISTS is as follows:

INSERT INTO table(field1, field2, fieldn) SELECT ‘field1‘, ‘field2‘, ‘fieldn‘ FROM DUAL WHERE NOT EXISTS(SELECT field FROM table WHERE field = ?)

The DUAL is a temporary table that does not need to be physically created, so it can be used.

The transformation for the card example above is as follows:

INSERTinto card (Cardno, Cardnum)SELECT' 111 ',' 100 'From DUALWHEREnot EXISTS (SELECT Cardno from card WHERE Cardno = ' 111 ');  INSERT into card (Cardno, cardnum) SELECT ' 222 ', ' $ ' from DUAL WHERE not EXISTS (
                          
                           select Cardno from 
                           card WHERE Cardno = ' 222 ');   
                               

Get!

MySQL Insert Insert Condition judgment: insert if not present

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.