'Making use of SQL UNIQUE KEY to prevent duplicates in Wordpress and $wpdb
I'm fairly new to DB architecture, and am creating a basic lookup table with the following structure for a Wordpress application. It simply stores two post ids to associate an "entity" post with a "news" post:
(
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
news_id int (20) unsigned NOT NULL,
entity_id int (20) unsigned NOT NULL,
PRIMARY KEY (id),
KEY (news_id),
KEY (entity_id),
UNIQUE KEY entity_news (news_id, entity_id)
)
My application will regularly attempt to store an association that already exists in the database, as there is a background process that regularly checks for new data.
It is my understanding that I can elegantly prevent duplicates by the use of a UNIQUE KEY constraint, rather than manually searching the database for an existing entry and doubling the number of queries. However, Wordpress outputs a a Database error everytime there is a duplicate entry. I know I can disable errors using $wpdb->hide_errors() but that feels hacky and before doing so, I want to check I'm doing the right thing here?
tl;dr
Is it good practice to rely solely on MySQL to detect duplicates using a UNIQUE key or should I also be doing a manual query beforehand to check?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
