2010-03-01 36 views

Trả lời

6

Tất nhiên một cơ sở dữ liệu có thể có mối quan hệ như thế:

Users 
    id 
    name 
    address 

Snippets 
    id 
    user_id 
    body 

Comments 
    id 
    body 
    snippet_id 
    user_id 

Ví dụ:

--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 
1

Chắc chắn rồi.

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) 

Thiết lập khóa ngoại và bạn đã sẵn sàng.

+0

Ngoại trừ bảng Nhận xét cần phải cho phép null cho SnippetId như cách tôi đọc câu hỏi gốc, Người dùng có thể để lại nhận xét không liên quan đến đoạn trích. –

Các vấn đề liên quan