MySQL insert when record does not exist (insert if not exists)

Source: Internet
Author: User
Tags mysql insert

In MySQL, inserting (insert) A record is simple, but some special applications, before inserting a record, need to check whether the record already exists, only if the record does not exist to perform the insert operation, this article describes the solution of this problem.
question: I created a table to hold the customer information, I know I can insert the information into the table with the INSERT statement, but how can I guarantee that no duplicate records will be inserted?
Answer: You can prevent the insertion of duplicate records by using EXISTS conditional clauses.
Example one: inserting multiple records
Suppose you have a clients table with a primary key of client_id, you can use the following statement:
Code:

INSERT into clients (client_id, Client_name, Client_type) SELECT supplier_id, Supplier_name, ' advertising ' from suppliers Where NOT EXISTS (SELECT * from clients where clients.client_id = suppliers.supplier_id);

Example one: inserting a single record
Code:

INSERT into clients (client_id, Client_name, Client_type) SELECT 10345, ' IBM ', ' advertising ' from dual WHERE not EXISTS (s Elect * from clients where clients.client_id = 10345);

Using dual to make a table name allows you to follow the SELECT statement directly following the value of the field you want to insert, even if the value does not already exist in the current table.

MySQL insert when record does not exist (insert if not exists)

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.