mysql query - blog posts and comments with limit

元气小坏坏 提交于 2019-12-10 23:40:10

问题


I have 2 tables: comments & posts. I'd like to display a list of 15 posts and maximum 2 most recent comments under each blog post entry using mysql.

the database scheme looks like this

posts_table: 
post_id, post_txt, post_timestamp

comments_table: 
post_id, comment_txt, comment_timestamp

how should the mysql query look in order to select 15 posts and their related comments (max 2 most recent ones per post)?

thanks


回答1:


MySQL LIMIT

SELECT * FROM posts_table LIMIT 0, 15

And to pull the most recent comments:

SELECT * FROM comments_table ORDER BY comment_timestamp DESC LIMIT 0, 2

I'll leave it to you to JOIN the two queries together somehow...




回答2:


Firstly i would select the posts like so

$resource = mysql_query('SELECT * FROM posts LIMIT 0,10'); //your own query in place here to get posts

    $posts = array();
    while($row = mysql_fetch_assoc($resource))
    {
        $query = sprintf('SELECT * FROM comments WHERE post_id = %d',$row['post_id']);
        $comments = mysql_query($query);
        while($row2 = mysql_fetch_assoc($comments))
        {
            $row['comments'] = $row2;
        }
        $posts[] = $row;
    }

Then in your template/view

foreach($posts as $post)
{
   //Print out your main posts data here.
   foreach($post['comments'] as $comment)
   {
      //Print out your comments here!
   }
}

Hope this helps



来源:https://stackoverflow.com/questions/2954376/mysql-query-blog-posts-and-comments-with-limit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!