mysql查询 - 博客文章和评论有限制

时间:2010-06-02 01:05:20

标签: php mysql greatest-n-per-group

我有两张桌子:评论&帖子。我想在每个博客帖子条目下使用mysql显示15个帖子和最多2个最新评论的列表。

数据库方案看起来像这样

posts_table: 
post_id, post_txt, post_timestamp

comments_table: 
post_id, comment_txt, comment_timestamp

为了选择15个帖子及其相关评论(每个帖子最多2个帖子),mysql查询应如何查看?

感谢

2 个答案:

答案 0 :(得分:1)

MySQL LIMIT

SELECT * FROM posts_table LIMIT 0, 15

并提取最新评论:

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

我会留给你以某种方式将两个查询加在一起......

答案 1 :(得分:-1)

首先我会选择这样的帖子

$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;
    }

然后在你的模板/视图中

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

希望这有帮助