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: |
Copy code |
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 1: Insert a single record
Code:
The Code is as follows: |
Copy code |
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
Next let's take a look at php mysql's access request processing
The Code is as follows: |
Copy code |
$ Title = 'www. bKjia. c0m '; $ 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 database is queried multiple times and the code is redundant. You can use the method to exclude duplicate data as needed.
For more details, see http://www.bKjia. c0m/database/110/sql-mysql-duplicate-key.htm