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:
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?