【问题标题】:Design a simple relational database table to store friends of user information设计一个简单的关系数据库表来存储好友的用户信息
【发布时间】:2017-08-11 23:57:00
【问题描述】:

我有一个带有列的简单用户表

user_id PK
Name

还有一个带列的朋友表

user_id FK
friend_id FK

现在说朋友表商店

Table Friends
---------------
user_id friend_id
----------------
1      2
1      3
2      3

朋友关系是 现在要检索用户 1 的朋友列表,我可以这样做

SELECT friend_id FROM friends where user_id = 1;

但是由于它是双向关系,即使在查询的朋友表的 user_id 列中的任何地方都没有提到用户 3,我如何检索用户 3 的朋友列表?我是否必须在朋友表中进行 (3,1)、(3,2) 之类的冗余存储? 或者任何人都可以提出更好的架构?

【问题讨论】:

  • 这可以使用递归查询轻松解决。您使用的是哪个 DBMS?后格雷斯?甲骨文?
  • Mysql 数据库。 Phong,请赐教。
  • 为什么不把friend_id设置为主键?
  • 如果 user1 是 user2 的朋友,那么 user2 是 user1 的朋友,如果你没有像追随者这样的额外角色,那么存储 (1,2) 和 (2,1) 是多余的在这种情况下,您只能存储上述一对
  • @Phong6698 可能在说为什么不制作实体关系模型,但您已经制作了一个......

标签: sql database database-design foreign-keys


【解决方案1】:

如果 user1user2 的朋友,那么 user2user1 的朋友。

如果您没有像追随者这样的额外角色,那么存储 (1,2) 和 (2,1) 是多余的,在这种情况下,您可以只存储上述对中的一对并使用 @987654321 检索用户的朋友@和union

select u.user_id user, f1.friend_id friend
from users u
join friends f1 on u.user_id=f1.user_id
union
select u.user_id user, f2.user_id friend
from users u
join friends f2 on u.user_id=f2.friend_id

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-12
    • 2012-07-15
    • 2011-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多