How does one run the MySQL database when the record does not exist?

Source: Internet
Author: User

We all know that inserting an insert record in a MySQL database is very simple, but there are special applications. before inserting a record, we need to check whether this record already exists and perform the insert operation only when the record does not exist. This article describes the solution to this problem.

Classification: PHP/MySQL,

Key words: exists, insert, mysql,

Add this page:

Insert a record in a MySQL database. However, in some special applications, before inserting a record, you must check whether the record exists. The insert operation is performed only when the record does not exist, this article describes the solution to this problem.

Q: I have created a table to store customer information. I know that the insert statement can be used to insert information into the table. But how can I ensure that duplicate records are not inserted?

Answer: You can use the EXISTS condition to prevent duplicate records from being inserted.

Example 1: insert multiple records

Suppose there is a clients table with the primary key of client_id, you can use the following statement:

 
 
  1. Code:  
  2. INSERT INTO clients  
  3. (client_id, client_name, client_type)  
  4. SELECT supplier_id, supplier_name, 'advertising'  
  5. FROM suppliers  
  6. WHERE not exists (select * from clients  
  7. where clients.client_id = suppliers.supplier_id); 

Example 1: Insert a single record into the MySQL database

 
 
  1. Code:  
  2. INSERT INTO clients  
  3. (client_id, client_name, client_type)  
  4. SELECT 10345, 'IBM', 'advertising'  
  5. FROM dual  
  6. WHERE not exists (select * from clients  
  7. where clients.client_id = 10345); 

Using dual as the table name allows you to directly keep up with the values of the fields to be inserted after the select statement, even if these values do not exist in the current table.

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.