簡體   English   中英

COUNT個與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個,它輸出的Count值非常大,為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子句( 教程 ):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM