MySQL inserts when the record does not exist (insert if not exists)
In MySQL, inserting (insert) A record is very simple, but some special applications, before inserting the record, need to check whether this record already exists, only if the record does not exist, the insert operation, this article describes the solution to this problem.
In MySQL, inserting (insert) A record is very simple, but some special applications, before inserting the record, need to check whether this record already exists, only if the record does not exist, the insert operation, this article describes the solution to this problem.
Question: I created a table to hold the customer information, and I know that you can insert the information into the table with the INSERT statement, but how do you guarantee that you don't insert duplicate records?
Answer: You can prevent the insertion of duplicate records by using EXISTS conditional sentences.
Example one: inserting more than one record
Suppose you have a clients table with a primary key of client_id, you can use the following statement:
Copy 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 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 as a table name allows you to follow directly to the value of the field you want to insert after the SELECT statement, even if the values do not yet exist in the current table.