Modeling Friends and Followers in an RDBMS

橙三吉。 提交于 2019-12-04 08:45:04

问题


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 zero to many friends.
A User can have zero to many followers.

Friends and followers are both Users themselves.

~~~~~

What's the best way to model this?

Thanks!


回答1:


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
)


来源:https://stackoverflow.com/questions/669483/modeling-friends-and-followers-in-an-rdbms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!