I have a MySQL DB in which I store data about each user.
I would like to add a list of friends for each user. Should I create a table of friends for each user in the
Assuming your USER
table has a primary key called id
or something similar, use the following table:
DROP TABLE IF EXISTS `friends`;
CREATE TABLE `friends` (
`user_id` int(10) unsigned NOT NULL,
`friend_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`user_id`,`friend_id`),
KEY `FK_FRIENDS_2` (`friend_id`),
CONSTRAINT `FK_FRIENDS_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`),
CONSTRAINT `FK_FRIENDS_2` FOREIGN KEY (`friend_id`) REFERENCES `users` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
This setup supports that Peter is a friend of Mary, but Mary doesn't think of Peter like that. But the data exists to infer that Peter is an acquaintance for Mary...
The primary key being both columns also stops duplicates.