【问题标题】:SQL Modeling Follower/Followed Relationships For Social Networking社交网络的 SQL 建模追随者/被关注关系
【发布时间】:2012-04-07 19:30:24
【问题描述】:

我正在为我的网站构建社交图谱。用户将创建关系(形式为追随者/被追随者),其中每一方都可以独立地追随另一方。我的用户表如下所示:

Users table
 - UserId (PK, Auto-incrementing integer)

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

(a) 表格将每个“关注”操作作为单独的行保存。

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' 和 'followed by' 放置为类似 (b) 的列表

Relationships table
 - UserId (FK to Users.UserId)
 - FollowingUsers (e.g. 2,488,28,40)
 - FollowedBy (e.g. 2,488,28,40)

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

假设我希望扩大规模,尽管我知道“Facebook 的问题不是我的问题” - 首选哪个选项或其他哪个选项?

【问题讨论】:

    标签: sql scalability data-modeling relationships


    【解决方案1】:

    我会选择选项 A。

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

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

    关系表

    • RelationshipId
    • UserId(FK 到 Users.UserId)
    • 关系类型

    您现在可以连接用户了。

    案例 B 遵循 A:

    • 添加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”

    【讨论】:

      猜你喜欢
      • 2016-09-28
      • 2013-08-22
      • 2021-10-09
      • 2019-07-03
      • 2017-12-08
      • 2013-05-18
      • 1970-01-01
      • 1970-01-01
      • 2021-02-18
      相关资源
      最近更新 更多