2014-10-08 197 views
0

我在这里有一个共同的情况。我想为特定用户选择所有帖子及其评论。例如:为特定用户选择所有帖子及其评论

1) 

    Post: 
    1(PostId), SomeTitle, SomeText 
    2(PostId), SomeTitle, SomeText 
    Comments: 
    1, 1(PostId), CommentTitle, CommentText, UserId(1 - from another table) 
    2, 1(PostId), CommentTitle, CommentText, UserId(1 - from another table) 
    3, 2(PostId), CommentTitle, CommentText, UserId(2 - from another table) 
    4, 2(PostId), CommentTitle, CommentText, UserId(2 - from another table) 

我想选择,例如,首先发布在一个结果集中,然后在用户id的另一个结果集中发表评论。总之,我想选择所有用户评论的帖子及其评论。谁能帮我?我想创建一个与userId和postId作为参数的SP,但我有问题。

+0

所有职位相关的任何意见+的带有注释的呢?或某个用户​​发布的所有帖子?如果是这样,邮政记录如何与用户相关联? – 2014-10-08 20:08:34

+0

只有用户评论的帖子。用户无法发布新帖子,因此帖子和用户表之间没有关系。 – user1797770 2014-10-08 20:12:18

+0

提示,使用'外键'和'加入' – 2014-10-08 20:13:45

回答

1

这将选择所有帖子

SELECT * FROM Post WHERE PostID IN (SELECT PostID FROM Comments WHERE UserID = 1); 

此选择的所有帖子和评论:

SELECT * FROM Post AS P, Comments AS C WHERE C.PostID = P.PostID AND C.UserID = 1 group by C.CommentId; 

(未测试,但应工作)

+0

比你非常,这个工作像一个魅力 – user1797770 2014-10-08 20:30:56

1
SELECT p.SomeTitle, p.SomeText, c.CommentTitle, c.CommentText, c.UserID 
FROM post AS p 
LEFT JOIN Comments AS c 
     ON c.PostId = p.PostId 

,如果你想添加的信息关于使用谁从另一个表(我们称之为userTable)的用户,你可以添加这个:

LEFT JOIN userTable AS uT 
     ON uT.UserId = c.UserId 

此代码应返回即使你所有的职位,这些用各自的岗位

+0

谢谢,但我需要两个结果集 – user1797770 2014-10-08 20:40:50

相关问题