简体   繁体   English

通过单个查询获取帖子及其所有评论

[英]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.评论表与帖子表相关, comment_post_id与它所属的帖子的post_id匹配。 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.通过这个查询,我只得到第一个带有匹配comment_post_id的评论,我有点明白为什么。 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 所有帖子及其对特定用户的评论,但对我不起作用。

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.如果帖子有 3 条与之关联的评论,您将获得 3 行,每行都包含同一帖子的键/值对 + 这 3 条评论中的一条。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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