Modeling Friends and Followers in an RDBMS

前端 未结 1 855
青春惊慌失措
青春惊慌失措 2021-02-04 21:24

I\'m trying to decide on the best way to model a relationship of records in a relational database. It\'s the classic friend/follow model:

~~~~

A User can have z

相关标签:
1条回答
  • 2021-02-04 22:02

    Users (UserId, ...)
    Subscription (Subscriber, Publisher)
    Friendship (FirstUser, SecondUser)

    CREATE TABLE Users (
        UserID int not null primary key,
        ...
    )
    
    CREATE TABLE Subscription (
        Subscriber int not null references Users(UserID),
        Publisher int not null references Users(UserID),
        constraint ck_NotEqual check (Subscriber <> Publisher)
    )
    
    CREATE TABLE Friendship (
        FirstUser int not null references Users(UserID), 
        SecondUser int not null references Users(UserID),
        constraint ck_Order check (FirstUser < SecondUser) -- since friendship is reflective
    )
    
    0 讨论(0)
提交回复
热议问题