MySQL prevents duplicate inserts of the same record insert if not exists

Source: Internet
Author: User
Tags php mysql table name

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.