【问题标题】:Comments on many tables database design issue多表数据库设计问题的评论
【发布时间】:2011-04-19 21:56:36
【问题描述】:

我有桌子:

Articles{...}
Recipes{...}
Notifications{...}
Photos{...}

我需要实现“用户 cmets”功能(如 facebook)。 我应该制作表格:ArticleComments, RecipesComments 等具有 1:n 关系吗? 或者为所有人创建一个Comments 表(但我不知道如何设计)?

【问题讨论】:

标签: mysql sql sql-server database database-design


【解决方案1】:

您可以创建另一个表CommentableEntity(尽管称它为更好的名称)。表中的每一行(ArticlesRecipes 等)都将引用此表中的唯一行。实体表可能有一个type 字段来指示实体的类型(以帮助反向连接)。

然后,您可以拥有一个以通用方式引用 CommentableEntityComment 表。

例如,您最终会得到以下表格:

Articles
-----------------
Article_id
CommentableEntity_id (fk, unique)
Content
....

Recipes
-----------------
Recipe_id
CommentableEntity_id (fk, unique)
Content
....

CommentableEntity
-----------------
CommentableEntity_id (pk)
EntityType (e.g. 'Recipe', 'Article')

Comment
-------
Comment_id (pk)
CommentableEntity_id (fk)
User_id (fk)
DateAdded
Comment 
...etc...

您可以在每次添加文章/食谱等时添加 CommentableEntity 记录。您的评论处理代码只需要知道 CommentableEntity_id - 它不关心它是什么类型的东西。

【讨论】:

  • 如果我理解你的建议是这样的: Articles{ArticleId...} Reciper{RecipeId...} CommmentableEntity{EntityId, UserId, CommentId, Date} // 这里 EntityId 是文章的 ID, recipse 等 Comments{CommentId, Text} 这是好的设计吗?
  • 我已经添加到我的答案中 - 希望这将有助于描述我的意思
【解决方案2】:

这取决于您的应用程序将如何使用 cmets。

我的猜测是,无论用户评论的实体如何,您都会经常想要提取用户创建的所有 cmets。也就是说,我假设您经常需要一个查询,该查询返回指示用户 JohnDoe 对文章 1 发表评论的行,然后是照片 12,然后是食谱 171。如果是这种情况,那么拥有一个 @987654321 会更有意义@ 表的结构类似于 Steve Mayne 建议的 CommentableEntity 表。

另一方面,如果您只访问特定项目的 cmets(即第 1 条的所有 cmets),则单独的 ArticleCommentsPhotoComments 表可能更合适。这使得实体表和注释表之间的外键更容易,并且可能更有效,因为它是一个穷人的分区。当然,一旦您开始不得不合并来自多个评论表的数据,这种效率就会消失,因此您需要对用例有足够的信心。

【讨论】:

    【解决方案3】:

    最简单的方法是拥有一个“多态”cmets 表,该表将包含它所引用的对象的 id 和类型的列。

    您可以执行以下操作:

    SELECT * FROM Comments where type = "Articles" and type_id = 1;
    SELECT * FROM Comments where type IN ("Recipes", "Photos")
    

    在 (type, id) 上放置一个唯一的复合索引也将提高查找的性能。

    【讨论】:

      【解决方案4】:
      SELECT TOP 1000 [Comments_Id]
            ,[Comments_Text]
            ,[Comments_IsApproved]
            ,[Comments_IsVisible]
            ,[Comments_DateStamp]
            ,[Type_Id]
            ,[Entity_Id] -- From Entity Table, listing Articles, Recipes etc. 
            ,[EntityItem_Id] -- One of the PK from table of Articles, Recipes etc.
            ,[User_Id]
        FROM [tbl_Comments]
      

      【讨论】:

        【解决方案5】:

        要了解如何为所有对象创建单个Comments 表,您可以查看django comment model (http://docs.djangoproject.com/en/dev/ref/contrib/comments/models/)

        【讨论】:

        • 目标链接不见了
        猜你喜欢
        • 1970-01-01
        • 2012-08-22
        • 1970-01-01
        • 2013-11-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-27
        相关资源
        最近更新 更多