Monday, 27 August 2018

Mysql query with GROUP BY does 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";
       }


You fetch your first row in the if clause , so in the while you are echoing 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.

0 comments:

Post a Comment