Can my database have a triangular relationship?

Take the tables: user, comment, fragment.

A user can have many fragments. A fragment can have many comments. The user can leave a lot of comments.

In turn, when I draw things, I get something like a triangle.

User 1-------------* Comment
      \           / 
       \         /
        *Snippet 1
+5
source share
2 answers

Of course, a database can have this relationship:

Users
  id
  name
  address

Snippets
  id
  user_id
  body

Comments
  id
  body
  snippet_id
  user_id

<strong> Examples:

--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
+6
source

That's right.

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)

Set up foreign keys and everything will be installed.

+1
source

All Articles