Home >Database >Mysql Tutorial >How to Ignore Duplicate Key Inserts in SQL Without Errors?

How to Ignore Duplicate Key Inserts in SQL Without Errors?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-27 16:05:11838browse

How to Ignore Duplicate Key Inserts in SQL Without Errors?

How to Ignore Duplicate Keys on Insert?

You're attempting to insert data into a table where the tag field has a UNIQUE constraint. To disregard any duplicate tags, you seek a solution that ignores these duplicate insertions.

Solution:

Instead of using INSERT IGNORE, which suppresses all errors, consider using the following approach:

INSERT INTO table_tags (tag) VALUES ('tag_a'),('tab_b'),('tag_c')
ON DUPLICATE KEY UPDATE tag=tag;

Explanation:

By using ON DUPLICATE KEY UPDATE, if any tag already exists in the database, its value will not be updated. This means that duplicate insertions will be ignored without causing an error. The code you provided with the "*" will not work as it does not specify which tag should be ignored.

Example:

When you execute the above query, you will notice that the following message is displayed:

Query OK, 0 rows affected (0.07 sec)

This indicates that the data was inserted successfully, with any duplicate tags being ignored.

The above is the detailed content of How to Ignore Duplicate Key Inserts in SQL Without Errors?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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