简体   繁体   中英

COUNT a number of database rows affiliated with an id

I'm creating a forum and right now I am trying to figure out how to count the number of replies in a topic. I am wanting to count the number of rows per topic_id #. So if there is a topic id of 5 and there are 10 rows in my database of topic_id #5, I want the it to count and output 10.

I tried to structure my query like this

 $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")

All this did however was mess up my original query which was this...

$query2 = mysqli_query($con,"SELECT * FROM forum_topics WHERE `category_id` ='".$cid."' ORDER BY topic_reply_date DESC")

And it is now only showing 1 topic rather than the 15 I have and it it outputting a very large Count figure of 406.

How can I get the following code to only count the topic_id associated with the topic that is being outputted and still allow for all of my topics to be outputted?

$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>";
    }

Use GROUP BY clause ( 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

Also note that OUTER JOIN is used in my example (instead of CROSS JOIN in your example).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM