【问题标题】:3 Table into 1 table3表成1表
【发布时间】:2023-03-22 19:27:01
【问题描述】:

假设我们有 contentsgalleriesquestions 的 3 个表和 comments 的 1 个表,如下所示:

**Contents**
--------------
ContentID | Title | Body

**Galleries**
--------------
GalleryID | Title | Rank

**Questions**
-------------
QuestionID | Title | Body | SendDate

**Comments**
------------
CommentID | Name | Body | ContentID | GalleryID | QuestionID

Comments 表连接到其他 3 个表的标准方法是什么?在Comments 表中使用其他三个表的外键是否正确?

【问题讨论】:

  • 查看答案应该很清楚,您需要明确说明您的系统是如何工作的。评论是否只针对另一个表?它是特定于所有三者的组合吗?
  • @Tom:每个评论都特定于一个特殊的表格

标签: sql sql-server relationship


【解决方案1】:

没错,但最好有一个 Commentable Table,其他 3 个表都继承自该表。像这样:

Commentable(CID, title)

所有内容、画廊和问题,首先应该插入到 Commentable 中,然后插入到它们自己的表格中。所以其他表会是这样的:

Contents( CID, Body)
Galleries(CID, Rank)
Questions(CID, Body, SendDate)

并且评论将与可评论相关联,所以

Comments(CommentID, Name, Body, CID)

最后,如果您需要指定评论是来自画廊、问题还是内容,您可以输入一个字段(即类型)来显示可评论的类型。这种方式将减少冗余并且具有更合理的设计。

【讨论】:

    【解决方案2】:

    是的,如果您想将Comments 绑定到连接到特定Contents 中特定ContentsQuestions,这是连接表的标准方式。

    但如果Questions 只考虑特定的ContentsContents 只存在于特定的Galleries 中,那么您的模型会更像

    Contents
    --------------
    ContentID
    GalleryID
    Title
    Body
    
    
    Galleries
    --------------
    GalleryID
    Title
    Rank
    
    
    Questions
    -------------
    QuestionID
    ContentID
    Title
    Body
    SendDate
    
    
    Comments
    ------------
    CommentID
    Name
    Body
    QuestionID
    

    【讨论】:

      【解决方案3】:

      另一种方法是使用连接器表,但您需要其中三个:

      Contents       ContentComments   
      - ContentID    - ContentID            <-- (ContentID,CommentID) as PK, 
      ...            - CommentID                ContentID as FK, CommentID as FK...
      
      Galleries      GalleryComments
      - GalleryID    - GalleryID
      ...            - CommentID
      
      Questions      QuestionComments
      - QuestionID   - QuestionID
      ...            - CommentID
      
      Comments
      - CommentID
      - Name
      - Body
      

      【讨论】:

      • 这仅适用于多对多关系(即同一评论可以属于多个画廊)
      • @Tom H. 是的,你当然是对的 :) 一个连接器表就足够了,或者只保留作者的布局
      【解决方案4】:

      如果每条评论都与一个内容项、一个图库项和一个问题相关联,那么这是正确的方式。

      如果每条评论仅与内容项、图库项或问题相关联,您应该使用三个表格来连接它们,就像 Matten 展示的那样。

      【讨论】:

        猜你喜欢
        • 2018-01-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-12
        • 2020-03-31
        相关资源
        最近更新 更多