[英]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.