You can prevent duplicate records from being inserted 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:
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 one: inserting 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 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
Here's a look at php mysql processing Shantiu
The code is as follows |
Copy Code |
$title = ' www.111cn.net '; $sql = "SELECT * FROM tablename where title= ' $title '"; $query = mysql_query ($sql); if (mysql_num_rows ($query)) { Exit (' cannot repeat the same record '); } Else { $sql = "Insert tablename VALUES (' $title ')"; mysql_query ($sql); Exit (' Save record successful '); }
|
The bad thing about this is that the database is queried multiple times, and the code is redundant, so that you can use the method of excluding duplicate data to your own situation.
For more details please see: http://www.111cn.net/database/110/sql-mysql-duplicate-key.htm