Home > Database > Mysql Tutorial > How to Insert New Records into MySQL While Handling Duplicate Entries?

How to Insert New Records into MySQL While Handling Duplicate Entries?

DDD
Release: 2024-12-28 04:55:13
Original
423 people have browsed it

How to Insert New Records into MySQL While Handling Duplicate Entries?

Inserting New Records While Ignoring Duplicate Entries in MySQL

In PHP, you may encounter a scenario where you need to insert multiple records into a database with unique fields. To ensure that only new records are inserted without encountering duplicate entry errors, consider the following approaches:

1. INSERT... IGNORE Syntax

This syntax allows MySQL to ignore duplicate entries without raising any errors. For example:

INSERT IGNORE INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);
Copy after login

2. REPLACE INTO Syntax

Unlike INSERT... IGNORE, the REPLACE INTO syntax overwrites existing records with the same key value. This can be useful if you want to update the values of existing records:

REPLACE INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);
Copy after login

3. INSERT... ON DUPLICATE KEY UPDATE Syntax

This syntax allows you to specify an update statement to be executed if a duplicate key is encountered. For example, to update the value of a column in a duplicate record:

INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...) ON DUPLICATE KEY UPDATE column2 = newValue;
Copy after login

Examples

Suppose you have a table named tbl with columns id and value, with the record>

  • REPLACE INTO

    REPLACE INTO tbl VALUES (1, 50);
    Copy after login

    This would update the record with>

  • INSERT IGNORE

    INSERT IGNORE INTO tbl VALUES (1, 10);
    Copy after login

    This would ignore the duplicate entry and no record would be inserted.

  • INSERT... ON DUPLICATE KEY UPDATE

    INSERT INTO tbl VALUES (1, 200) ON DUPLICATE KEY UPDATE value=200;
    Copy after login

    This would update the record with>

The above is the detailed content of How to Insert New Records into MySQL While Handling Duplicate Entries?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template