【发布时间】:2020-11-01 21:18:38
【问题描述】:
您将如何以尽可能最好和最高性能的方式为类似 twitter 的应用程序设计数据库?
在这个应用程序中,用户可以发推文、回复和转发。推文、回复和转发最终会创建一条新推文。所以我们可以很容易地创建这样的模式:
tweets
- id - integer
- text - string -> this is non nullable
- userId - integer
- createdAt - date
- parentId - integer -> when replying, this will be the parent tweet of the reply
- isRetweet - boolean -> this becomes true only when the current tweet is a retweet. The parentId will have the id of the tweet that was retweeted
但是让我们介绍另一个功能:用户可以在不写text 的情况下转发推文(这是 Twitter 目前的工作方式)。在这种情况下,我们必须使我们的text 列可以为空。突然之间,这意味着我们可以在没有 text 的情况下创建推文和回复,因为不再有关于此的数据库限制(现在让我们忽略应用层验证)。
我的方法是为此再创建 3 个表。最后我们将有 4 个表:
tweets
- id - integer
- text - string
- userId - integer
- createdAt - date
replies
- tweetId - integer -> this will contain the content of the reply
- parentId - integer -> this is the parent of the reply
retweetsWithText
- tweetId - integer -> this will contain the content of the retweet
- parentId - integer -> this is the parent of the retweet
retweetsWithoutText
- tweetId - integer -> this will contain the reference for the retweeted tweet
- userId - integer -> who retweeted the tweet. We need this because we won't save anything in the `tweets` table regarding retweets without text
- createdAt - date
我知道这可能查询起来很复杂,但最后我认为这将在存储方面带来最佳性能(不需要 parentId 和 isRetweet)。这也将解决没有文字转推的问题。第一种方法的另一个问题是 parentId 很可能为 null,因为根据统计数据,只有 30% 的推文得到评论或转发。所以我们最终会得到很多用于 parentId 的 NULL 列
有没有更简单的方法来解决这个问题,表格更少,最好没有空/冗余单元格?
【问题讨论】:
标签: database twitter relational-database database-schema