简体   繁体   中英

Get post and all its comments via single query

I am building a simple blog. Comments table is related to posts table w/ comment_post_id matching post_id of the post it belongs to. Now, I am trying to pull both post and all its comments via single query:

SELECT * 
FROM posts 
LEFT JOIN comments 
ON post_id=comment_post_id

With this query I get only the first comment w/ matching comment_post_id , and I kinda understand why. What would be a query that pulls all of them? Looked at this answer Select all post and its comments for a specific user , but did not work for me.

SELECT * 
FROM posts 
LEFT JOIN comments 
ON posts.post_id=comments.comments_post_id 
WHERE post_id=$id

If post has 3 comments associated with it you get 3 rows, and each of those contain key/value pairs of the same post + one of those 3 comments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM