0

I have a Relationships table that I am trying to add a composite index to:

CREATE UNIQUE INDEX idx_relationship_userid_friend_id on Relationships(user_id, friend_id);

I would like to prevent duplicate entries for user_id and friend_id columns. i.e. Second entry of user_id = 26 and friend_id = 46 should give an error.

I ran the command above. When I run the command again, I get the following error: Duplicate entry '36-50' for key 'idx_relationship_userid_friend_id'

When I look at the structure in for INDEXES I see the following table:

enter image description here

Under table info next to Create syntax, I have the following code:

CREATE TABLE `Relationships` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `friend_id` int(11) DEFAULT NULL,
  `status` int(11) DEFAULT '1',
  `createdAt` datetime NOT NULL,
  `updatedAt` datetime NOT NULL,
  `user_id` int(11) DEFAULT NULL,
  `app_common` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `owner_id` (`user_id`),
  KEY `app_common` (`app_common`),
  CONSTRAINT `Relationships_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `Users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `Relationships_ibfk_2` FOREIGN KEY (`app_common`) REFERENCES `AppCommon` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=79 DEFAULT CHARSET=latin1;

However, I am able to insert duplicate records in the database.

Question: How can I avoid duplicate entries?

Flimzy
  • 68,325
  • 15
  • 126
  • 165
user1107173
  • 9,626
  • 14
  • 67
  • 111

2 Answers2

0

Use the Unique constraint to handle your issue, something like:

CONSTRAINT UC_user_friend UNIQUE (user_id, friend_id)
Fabien
  • 4,614
  • 2
  • 16
  • 33
StanislavL
  • 56,113
  • 9
  • 64
  • 93
0

Since your table already has duplicates, it gets an error trying to create the index, so it doesn't add it.

See How to delete duplicates on a MySQL table? for how to remove duplicates. Once you've done that you can add the unique index to prevent new duplicates from being added.

Barmar
  • 669,327
  • 51
  • 454
  • 560
  • Thanks. I tried running the following command, `ALTER IGNORE TABLE Relationships ADD UNIQUE (user_id, friend_id)`. I got an error. I believe it's because that command is deprecated. – user1107173 Aug 09 '17 at 14:46
  • You're right, it was removed in 5.7. https://dev.mysql.com/worklog/task/?id=7395. You need to use some other method to get rid of your duplicates before you can add the index. – Barmar Aug 09 '17 at 14:49