views:

96

answers:

2

Take tables: User, Comment, Snippet.

A User can have many Snippets. A Snippet can have many Comments. A User can leave many Comments.

In turn, when I diagram things, I end up with something like a triangle.

User 1-------------* Comment
      \           / 
       \         /
        *Snippet 1
+6  A: 

Of course a database can have relationships like that:

Users
  id
  name
  address

Snippets
  id
  user_id
  body

Comments
  id
  body
  snippet_id
  user_id

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
Mike Trpcic
+1  A: 

Absolutely.

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 your foreign keys and you're all set.

roufamatic
Except wouldn't the Comments table need to allow nulls for SnippetId as the way I read the original question, Users can leave comments not related to a snippet.
Stuart Helwig