![](/img/trans.png)
[英]How can I modify this query so that I can sort the results by the number of comments each post has?
[英]SQL query on how to Count the number of comments each post have
我有两个名为“评论”和“帖子”的数据库表
在“posts”表中我得到了post_id,post_title
在“评论”表中,我收到了comment_id,post_id,message
评论表中的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()
您只需要一个查询,将“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";
}
您可以使用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 />";
}
在你的代码中, WHERE post_id='$postid'";
它应该是"WHERE post_id=" + $postid +";";
因为你没有添加变量只是在其中创建一个带有变量名的长字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.