MySQL friends table

后端 未结 5 1877
没有蜡笔的小新
没有蜡笔的小新 2020-12-08 08:32

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

5条回答
  •  既然无缘
    2020-12-08 08:50

    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.

提交回复
热议问题