Home >Database >Mysql Tutorial >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!