Database 我的数据库可以有三角关系吗?

Database 我的数据库可以有三角关系吗?,database,database-design,Database,Database Design,获取表格:用户、注释、代码段 一个用户可以有许多代码段。 一个代码段可以有许多注释。 用户可以留下许多评论 反过来,当我画东西的时候,我最终得到了一个类似三角形的东西 User 1-------------* Comment \ / \ / *Snippet 1 当然,数据库可以有这样的关系: Users id name address Snippets id user_id body

获取表格:用户、注释、代码段

一个用户可以有许多代码段。 一个代码段可以有许多注释。 用户可以留下许多评论

反过来,当我画东西的时候,我最终得到了一个类似三角形的东西

User 1-------------* Comment
      \           / 
       \         /
        *Snippet 1

当然,数据库可以有这样的关系:

Users
  id
  name
  address

Snippets
  id
  user_id
  body

Comments
  id
  body
  snippet_id
  user_id
示例:

--Get all comments by a user
SELECT * FROM comments WHERE user_id = 1

--Get all snippets by a user
SELECT * FROM snippets WHERE user_id = 1

--Get all comments on a snippet
SELECT * FROM comments WHERE snippet_id = 1

--Get all comments on a particular snippet by a particular user
SELECT * FROM comments WHERE snippet_id = 1 AND user_id = 1
当然

create table Users (Id int not null primary key identity(1,1))
create table Snippets (Id int not null primary key identity(1,1), 
                       UserId int not null)
create table Comments (Id int not null primary key identity(1,1),
                       SnippetId int not null,
                       UserId int not null)

设置外键后,一切都已设置。

除了注释表不需要为SnippetId允许空值外,正如我阅读原始问题的方式一样,用户可以留下与代码段无关的注释。