Mysql prevents repeated inserts of the same record insert if not exists

Source: Internet
Author: User

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

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.