关于如何计算每个帖子的评论数量的SQL查询

时间:2015-08-31 03:48:15

标签: php mysql

我有两个数据库表名为" comments"和"帖子"

在"帖子"我得到了post_id,post_title

在"评论"表我得到了comment_id,post_id,消息

评论表中的post_id存储正在评论的帖子的ID。通过这种方式,我可以计算帖子中有多少评论。

我尝试做研究并最终得到以下代码:

$displaypost = "SELECT * FROM posts";
$result = $conn->query($displaypost);

if ($result->num_rows > 0) {

    while($row = $result->fetch_assoc()) {
        $postid = $row['post_id'];
        $posttitle =$row['post_title'];

        $countdata = "SELECT COUNT(post_id) FROM comments WHERE post_id='$postid'";
        $countresult = $conn->query($countdata);
        $countrow = mysqli_fetch_row($countresult); 
        $total_comment = $countrow[0];
        echo "Post Title: $posttitle";
        echo "Post Comment: $total_comment";
    }
} else {
    echo "0 results";
}

上面的代码结果为:

  

无法获取mysqli_fetch_row()

3 个答案:

答案 0 :(得分:3)

您只需要一个查询,替换" SELECT * FROM posts"由

    SELECT post_title,count(posts.post_id) as Total FROM posts JOIN comments WHERE posts.post_id = comments.post_id GROUP BY posts.post_id

然后你会有

      $posttitle = $row['post_title'];
      $total_comment =$row['Total'];

      echo "Post Title: $posttitle";
      echo "Post Comment: $total_comment";

最终代码

 $displaypost = "SELECT post_title,count(posts.post_id) as Total FROM posts JOIN comments WHERE posts.post_id = comments.post_id GROUP BY posts.post_id";
 $result = $conn->query($displaypost);

if ($result->num_rows > 0) {

while($row = $result->fetch_assoc()) {
      $posttitle = $row['post_title'];
      $total_comment =$row['Total'];

      echo "Post Title: $posttitle";
      echo "Post Comment: $total_comment";
}
} else {
echo "0 results";
}

答案 1 :(得分:2)

您可以使用SQL Join和Gouping子句一次完成所有操作

SELECT Posts.*,Count(Comments.*) as CommentCount FROM posts Posts LEFT JOIN comments Comments ON (Post.id = Comments.post_id) GROUP BY Post.id

https://dev.mysql.com/doc/refman/5.0/en/join.html

https://dev.mysql.com/doc/refman/5.1/en/group-by-handling.html

编辑:

     $query = "SELECT Posts.*,Count(Comments.*) as CommentCount FROM posts Posts LEFT JOIN comments Comments ON (Post.id = Comments.post_id) GROUP BY Post.id";  
     $result = $conn->query($query);
     while($row = $result->fetch_assoc()) {
         echo "Post ID: {$row['id']} has {$row['CommentCount']} Comment(s)! <br />";
     }

答案 2 :(得分:0)

在您的代码WHERE post_id='$postid'";中 它应该是"WHERE post_id=" + $postid +";";因为您没有添加变量,只需创建一个带有变量名称的长字符串。