2014-10-08 188 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

相關問題