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

社交网络的SQL建模跟随者/跟随者关系,sql,scalability,data-modeling,relationships,Sql,Scalability,Data Modeling,Relationships,我正在为我的网站建立一个社交图。用户将创建关系(形式为follower/followerd),其中各方可以独立地跟随另一方。我的用户表如下所示: Users table - UserId (PK, Auto-incrementing integer) 考虑到如何对此进行建模,我提出了几种备选方案,例如: (a) 表将每个“follow”操作作为一个单独的行保存 Relationships table - FollowerId (FK to Users.UserId) - Followed

我正在为我的网站建立一个社交图。用户将创建关系(形式为follower/followerd),其中各方可以独立地跟随另一方。我的用户表如下所示:

Users table
 - UserId (PK, Auto-incrementing integer)
考虑到如何对此进行建模,我提出了几种备选方案,例如:

(a) 表将每个“follow”操作作为一个单独的行保存

Relationships table
 - FollowerId (FK to Users.UserId)
 - FollowedId (FK to Users.UserId)
这有一个缺点,即对于许多用户,它将创建大量的行

(b) 一个表包含每个用户所遵循的CSV或其他结构的用户列表:

Relationships table
 - FollowerId (FK to Users.UserId)
 - FollowingUsers (e.g. 2,488,28,40)
这有一个缺点,即查询将更加复杂(而且代价高昂?)。我还必须保持字符串值的顺序,等等

(c) 每行的关系,其中用户可能位于关系的任意一方:

Relationships table
 - Party1Id (FK to Users.UserId)
 - FollowingParty2 (boolean)
 - Party2Id (FK to Users.UserId)
 - FollowingParty1 (boolean)
这将在(a)上保存行,但查询更复杂,因为用户可能是任何一方

(d) 将“following”和“following by”列为(b)类列表

这似乎是最好的,但现在我必须使用事务来更新多行

假设我希望扩大规模,尽管意识到“Facebook的问题不是我的问题”-哪个选项,或者哪个选项更可取?

我会选择选项a

  • 任何类型的社会图表分析都不可能使用其他选项
  • 使用其他选项强制执行任何类型的关系约束都是不可能的
  • 如果您不打算以关系方式存储数据,则无需使用关系数据库
  • 一个有趣的选择可能是考虑关系表模型:

    关系表

    • 关系ID
    • UserId(FK到Users.UserId)
    • 关系类型
    您现在可以连接用户

    案例B遵循A:

    • 添加RelationshipId1,UserAId,“IsFollowerd”
    • 添加RelationshipId1,UserBId,“IsFollowing”
    如果其他用户开始执行以下操作:

    • 添加RelationshipId1,另一个用户ID“IsFollowing”
    如果另一个用户开始执行以下操作B:

    • 添加RelationshipId2,另一个用户ID“IsFollowing”
    如果愿意,您甚至可以删除不需要的行: A从B开始:

    • 添加RelationshipId3,用户帮助,“IsFollowAndIsFollow”
    • 添加RelationshipId3,UserBId,“IsFollowAndIsFollow”
    • 删除关系ShipID1,UserBId,“IsFollowing”
    Relationships table
     - UserId (FK to Users.UserId)
     - FollowingUsers (e.g. 2,488,28,40)
     - FollowedBy (e.g. 2,488,28,40)