计算与 id 关联的数据库行数

COUNT a number of database rows affiliated with an id

我正在创建一个论坛,现在我正在尝试弄清楚如何计算某个主题中的回复数。我想计算每个 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>";
    }

使用 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)。