我正在创建一个论坛,现在我正在试图弄清楚如何计算某个主题中的回复数量。我想要计算每个topic_id#的行数。因此,如果主题ID为5且我的topic_id#5数据库中有10行,我希望它计数并输出10。
我尝试像这样构建我的查询
$query2 = mysqli_query($con,"SELECT t.*, COUNT(p.topic_id) AS tid2 FROM forum_topics AS t, forum_posts AS p ORDER BY topic_reply_date DESC")
然而,所有这一切都搞砸了我的原始查询,这就是......
$query2 = mysqli_query($con,"SELECT * FROM forum_topics WHERE `category_id` ='".$cid."' ORDER BY topic_reply_date DESC")
它现在只显示1个主题,而不是我拥有的15个主题,它输出的数量非常大,为406个。
如何才能获得以下代码,仅计算与正在输出的主题相关的topic_id,并仍允许输出我的所有主题?
$query2 = mysqli_query($con,"SELECT t.*, COUNT(p.topic_id) AS tid2 FROM forum_topics AS t, forum_posts AS p ORDER BY topic_reply_date DESC")
or die ("Query2 failed: %s\n".($query2->error));
$numrows2 = mysqli_num_rows($query2);
//if ( false===$query2 ) {
// die(' Query2 failed: ' . htmlspecialchars($query2->error));
//}
if($numrows2 > 0){
$topics .= "<table width='100%' style='border-collapse: collapse;'>";
//Change link once discussion page is made
$topics .= "<tr><td colspan='3'><a href='discussions.php'>Return to Discussion Index</a>".$logged."<hr /></td></tr>";
$topics .= "<tr style='background-color: #dddddd;'><td>Topic Title</td><td width='65' align='center'>Replies</td><td width='65'
align='center'>Views</td></tr>";
$topics .= "<tr><td colspan='3'><hr /></td></tr>";
while($row = mysqli_fetch_assoc($query2)){
$tid = $row['id'];
$title = $row['topic_title'];
$views = $row['topic_views'];
$replies = $row['tid2'];
$date = $row['topic_date'];
$creator = $row['topic_creator'];
$topics .= "<tr><td><a href='forum_view_topic.php?cid=".$cid."&tid=".$tid."'>".$title."</a><br /><span class='post_info'>Posted
by: ".$creator." on ".$date."</span></td><td align='cener'>".$replies."</td><td align='center'>".$views."</td></tr>";
$topics .= "<tr><td colspan='3'><hr /></td></tr>";
}
答案 0 :(得分:1)
使用GROUP BY
子句(tutorial):
SELECT t.*, COUNT(p.topic_id) AS tid2
FROM forum_topics AS t JOIN forum_posts AS p on t.id = p.topic_id
GROUP BY t.id
另请注意,我的示例中使用了OUTER JOIN
(而不是示例中的CROSS JOIN
)。