简体   繁体   中英

mysql query with GROUP BY not get all rows

I have 2 tables:

awards:

awardsid,
forumid

forum:

forumid,
title

When I make a query to get all forums with count of awards for that forum, the query does not return all rows. If database Contain 4 rows it only returns 3. The result is always 1 less row than what is expected.

$forumdata = $db->query_read(" SELECT COUNT(awards.forumid) AS awardscount,forum.title,awards.forumid
FROM " . TABLE_PREFIX . " awards AS awards
 INNER JOIN " . TABLE_PREFIX . " forum AS forum ON (forum.forumid = awards.forumid)
 GROUP BY awards.forumid ");
       if($db->fetch_array($forumdata))
       {

                while ($awards = $db->fetch_array($forumdata))
                {
                $title .= $awards['title'];
                $awardscount .= $awards['awardscount'];
                echo $title.':'.$awardscount.'<br />';
                }
       }
       else
       {
        echo "No Data";
       }

Change your:

 while ($awards = $db->fetch_array($forumdata))
                {
                $title .= $awards['title'];
                $awardscount .= $awards['awardscount'];
                echo $title.':'.$awardscount.'<br />';
                }

to

do
                {
                $title .= $awards['title'];
                $awardscount .= $awards['awardscount'];
                echo $title.':'.$awardscount.'<br />';
                }
while ($awards = $db->fetch_array($forumdata));

You are reading it twice in the beginning before processing

You fetch your first row in the if clause , so in the while you are echo ing rows from 2 to n . I don't know how you are implementing your class to access mysql, so you can use something like this :

echo isset($title) ? '' : 'No data';

After your while loop and of course you should get rid of your if/else clauses in the way they are presented now.

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