When we store database data, we often use related server scripts to prevent duplicate data storage. today we use the insertifnotexists condition to prevent duplicate records from being inserted.
When we store database data, we often use related server scripts to prevent duplicate data storage. today we use the insert if not exists condition to prevent duplicate records from being inserted.
You can use the EXISTS condition to prevent repeated 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:
| The code is as follows: |
|
|
Insert into clients
(Client_id, client_name, client_type)
SELECT supplier_id, supplier_name, 'Advertising'
FROM suppliers
WHERE not exists (* from clients
Where clients. client_id = suppliers. supplier_id ); |
Example 1: insert a single record
Code:
| The code is 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 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
The following describes how to handle access requests.
| The code is as follows: |
|
$ Title = 'www .111cn.net ';
$ SQL = "Select * from tablename where title = '$ title '";
$ Query = mysql_query ($ SQL );
If (mysql_num_rows ($ query ))
{
Exit ('record cannot be inserted repeatedly ');
}
Else
{
$ SQL = "insert tablename values ('$ title ')";
Mysql_query ($ SQL );
Exit ('record saved successfully ');
}
|
// The bad thing about this method is that the query is performed multiple times and the code is redundant. you can use the method to exclude duplicate data as needed.
For more details, see: