On duplicate key ignore?

Mysql

Mysql Problem Overview


I'm trying to finish this query; my tag field is set to UNIQUE and I simply want the database to ignore any duplicate tag.

INSERT INTO table_tags (tag) VALUES ('tag_a'),('tab_b'),('tag_c')
ON DUPLICATE KEY IGNORE '*the offending tag and carry on*'

or even this would be acceptable

INSERT INTO table_tags (tag) VALUES ('tag_a'),('tab_b'),('tag_c')
ON DUPLICATE KEY UPDATE '*the offending tag and carry on*'

Mysql Solutions


Solution 1 - Mysql

Would suggest NOT using INSERT IGNORE as it ignores ALL errors (ie its a sloppy global ignore). Instead, since in your example tag is the unique key, use:

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

on duplicate key produces:

> Query OK, 0 rows affected (0.07 sec)

Solution 2 - Mysql

Mysql has this handy UPDATE INTO command ;)

edit Looks like they renamed it to REPLACE

> REPLACE works exactly like INSERT, > except that if an old row in the table > has the same value as a new row for a > PRIMARY KEY or a UNIQUE index, the > old row is deleted before the new row > is inserted

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCodeChapView Question on Stackoverflow
Solution 1 - MysqlthummperView Answer on Stackoverflow
Solution 2 - MysqlByron WhitlockView Answer on Stackoverflow