In a table I’ve got 3 columns:
id
tag1
tag2
id is a primary key.
And i only want one unique tag1-tag2-combination in that table.
eg if one entry looks like:
id: 1
tag1: cat
tag2: dog
I dont want a second entry like this one beneath to get inserted:
id: 2
tag1: cat
tag2: dog
So i made all 3 columns primary keys but the problem is that then the second entry would get inserted since it looks in the combination of all 3 of them.
How do i solve this so that only the combination of the tag1 and tag2 is unique?
UPDATE: I added a unique contraint on tag1 and tag2. however, its still possible to insert:
id: 3
tag1: dog
tag2: cat
Is there a way to prevent this?
You should leave ID as the primary key, and then can create a unique constraint for the tag1 and tag2:
With the unique constraint, you will be guaranteed that you will never have two rows with duplicate tag1 and tag2 values.
EDIT:
Further to your last update, you cannot enforce that with unique constraints. Keep in mind that for the database a record with (tag1 = dog, tag2 = cat) is totally different from a record with (tag1 = cat, tag2 = dog).
Probably your best bet is to redesign your database schema, as follows:
Then you can simply set (message_id, tag_id) of the “tag_messages” table as a primary key. This will automatically enforce that there cannot be any message with a duplicate tag.
Some sample data: