In MySQL, inserting a record is very simple, but in some special applications, before inserting a record, you need to check whether the record already 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:
Code:
INSERT INTO clients(client_id, client_name, client_type)SELECT supplier_id, supplier_name, supplier_typeFROM suppliersWHERE not exists (select * from clientswhere clients.client_id = suppliers.supplier_id);
Example 2: Insert a single record
Code:
INSERT INTO clients(client_id, client_name, client_type)SELECT 10345, ’IBM’, ’advertising’FROM dualWHERE not exists (select * from clientswhere 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.
Article Reprinted from: http://www.isclassic.net/archives/170
Articles you may be interested in
- Note the following when querying strings with single quotes and inserting strings with single quotes in Mysql:
- MySQL replace function replacement string statement usage
- Use the PHP function memory_get_usage to obtain the current PHP memory consumption for program performance optimization.
- Mysql database cache function analysis, debugging, and performance summary
- Conversion of date and unix timestamps in php and mysql
- MySQL large data volume quick insert method and statement Performance Optimization
- How does mysql export data of a field in a table?
- How does mysql view the space occupied by a table?