0

I'm trying to set a unique restraint on a combination of columns rather than on a single column. I have a table, "tags":

  • id (int, PK, AI, unsigned)
  • tag (varchar 25)
  • user_id (int, unsigned)

Following the answer to this question, I tried to set the combo restraint via:

ALTER TABLE `tags` ADD UNIQUE `unique_tag_user_combo` (`tag`, `user_id`);

So far, so good. But when I come to test it, by seeing if it will let me insert the same tag twice but with different user IDs (it should), it errors:

INSERT INTO `tags` VALUES (NULL, 'foo', '1'), (NULL, 'foo', '2')

...throws...

Duplicate entry 'foo' for key 'name_2' 

Remember the unique restraint is on the combo of tag + user_id, so this query, to my mind, should run fine. I could understand this error if I'd tried to insert foo/1 twice, but not foo/1 and foo/2. What am I missing?

(EDIT - also, what's that 'name_2' reference in the error message all about? I don't have a column with that name...)

Community
  • 1
  • 1
Mitya
  • 33,629
  • 9
  • 60
  • 107

1 Answers1

1

You might also have an unique index on tag column.Use

SHOW CREATE TABLE yourtb
Mihai
  • 26,325
  • 7
  • 66
  • 81