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 :(得分: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;
(未经测试,但应该有效)
答案 1 :(得分: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
此代码应该返回所有帖子,即使这些帖子没有评论+带有与各自帖子相关的评论的帖子