Skip to content Skip to sidebar Skip to footer

Select All Post And Its Comments For A Specific User

i have a common situation here. I want to select all posts and its comments for a specific user. For example: 1) Post: 1(PostId), SomeTitle, SomeText 2(PostId), Some

Solution 1:

This selects all posts

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

This select all posts and comments:

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

(Not tested, but should work)

Solution 2:

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

if you want to add information about the use who commented from another table (let's call it userTable), you can add this:

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

This code should return you ALL the posts even these with no comments + the ones with comments associated with their respective posts

Post a Comment for "Select All Post And Its Comments For A Specific User"