MySQL insert when record does not exist (insert if not exists)
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.
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:
Copy the Code code as follows:
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
Copy the Code code as follows:
INSERT into clients
(client_id, Client_name, Client_type)
SELECT 10345, ' IBM ', ' advertising '
From dual
WHERE NOT EXISTS (SELECT * 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 if not exists method to prevent the insertion of duplicate records (GO)