社交网络的SQL建模跟随者/关注关系

Har*_*per 5 sql scalability data-modeling relationships

我正在为我的网站构建社交图.用户将创建关系(表单跟随者/关注者),其中每个方可以独立地跟随另一方.我的用户表看起来像这样:

Users table
 - UserId (PK, Auto-incrementing integer)
Run Code Online (Sandbox Code Playgroud)

考虑如何对此进行建模,我提出了几种替代方案,例如:

(a)表格将每个"跟随"行动视为一个单独的行.

Relationships table
 - FollowerId (FK to Users.UserId)
 - FollowedId (FK to Users.UserId)
Run Code Online (Sandbox Code Playgroud)

这有一个缺点,即给定许多用户,它会产生大量的行.

(b)表格保存每个用户关注的用户列表,如CSV或其他结构:

Relationships table
 - FollowerId (FK to Users.UserId)
 - FollowingUsers (e.g. 2,488,28,40)
Run Code Online (Sandbox Code Playgroud)

这样做的缺点是查询会更复杂(而且代价高昂?).我还必须维护字符串值的排序等...

(c)每行的关系,用户可能位于关系的"侧":

Relationships table
 - Party1Id (FK to Users.UserId)
 - FollowingParty2 (boolean)
 - Party2Id (FK to Users.UserId)
 - FollowingParty1 (boolean)
Run Code Online (Sandbox Code Playgroud)

这会将行保存在(a)上,但查询更复杂,因为用户可能是任何一方.

(d)将"跟随"和"跟随"放在如(b)之类的列表中

Relationships table
 - UserId (FK to Users.UserId)
 - FollowingUsers (e.g. 2,488,28,40)
 - FollowedBy (e.g. 2,488,28,40)
Run Code Online (Sandbox Code Playgroud)

这似乎是所有世界中最好的,但现在我必须使用事务来更新多行.

假设我希望扩展到一个大尺寸,虽然意识到"Facebook的问题不是我的问题" - 哪个选项,或者其他选项是首选?

Gor*_*ran 5

我选择A.

  1. 使用其他选项无法进行任何类型的社交图分析
  2. 使用其他选项不可能实施任何类型的关系约束
  3. 如果您不打算以关系方式存储数据,则无需使用关系数据库.

一个有趣的选择可能是考虑关系表模型:

关系表

  • RelationshipId
  • UserId(FK到Users.UserId)
  • RelationType

您现在可以连接用户.

案例B如下:

  • 添加RelationshipId1,UserAId,"IsFollowed"
  • 添加RelationshipId1,UserBId,"IsFollowing"

case另一个用户开始关注A:

  • 添加RelationshipId1,AnotherUserId,"IsFollowing"

case另一个用户开始关注B:

  • 添加RelationshipId2,AnotherUserId,"IsFollowing"

如果您愿意,甚至可以删除不需要的行:A从B开始:

  • 添加RelationshipId3,UserAId,"IsFollowedAndIsFollowing"
  • 添加RelationshipId3,UserBId,"IsFollowedAndIsFollowing"
  • 删除RelationshipId1,UserBId,"IsFollowing"