简体   繁体   中英

How to print posts and comments with only one sql query

Is it possible to print out (PHP) all my blog posts + associated comments via one sql query?

If so, how?

I was thinking in this direction:

SELECT p.post_id, p.title, c.comment_body
FROM posts p
LEFT JOIN comments c
ON c.parent_id = p.post_id

But this didn't work out as I expected

Using one SQL query is not very convenient, since you have 1 post and multiple comments.
Having the post details added to each comment (in a combined query) is a waste of resources.

It is much more convenient to get the post details and use post_id of the post to find the comments belonging to the post.

If you're using MySQL you could use the GROUP_CONCAT function:

SELECT p.post_id, p.title, GROUP_CONCAT(c.comment_body)
FROM posts
LEFT JOIN comments c ON c.parent_id = p.post_id
GROUP BY p.post_id

The easiest way I can think of is to iterate through all the rows returned and group them into an associative array where keys are the post IDs. Then you can iterate through that associative array and print the comments for each post, taking the post title from the first row in the group.

When getting data just use the field name like: $result = mysql_query("SELECT p.post_id, p.title, c.comment_body FROM posts p LEFT JOIN comments c ON c.parent_id = p.post_id");

while($row = mysql_fetch_array($result))
  {
  echo $row['title'] . " " . $row['comment_body'];
  echo "<br />";
  }

From: http://www.tizag.com/mysqlTutorial/mysqljoins.php

For MySQL:

SELECT p.post_id, p.title, GROUP_CONCAT(c.comment_body), count(*) as coment_cnt
FROM
    posts p
        LEFT JOIN comments c ON (p.post_id = c.parent_id)
GROUP BY
    p.post_id

"But this didn't work out as I expected "

...but you don't say what you did expect.

Assuming that the the implied schema in your query is correct, then its a no brainer to only show the posts once:

$lastpostid=false;
while ($r=mysql_fetch_assoc($result)) {
  if ($r['post_id']!=$lastpost) {
     print "Post: " . $r['title'] . "<br />\n";
     $comment_id=1;
     $lastpost=$r['post_id'];
  }
  print "Comment # $comment_id : " . $r['comment_body'] . "<br />\n";
  $comment_id++;
}

But as I said this implies that your query is correct (ie that comments are not hierarchical).

C.

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