Boopathy
Boopathy

Reputation: 415

Getting the count of rows in each category in a MySQL table

Let me say, I have two tables category and questions. In questions table I have few or more questions under the same category and the table has questions of various categories.

I need the count of rows in each category under the question table.

Category: +----+--------+--+ | id | name | | +----+--------+--+ | 1 | Type 1 | | | 2 | Type 2 | | | 3 | Type 3 | | +----+--------+--+

Questions +----+------+-------+ | id | name | catid | +----+------+-------+ | 1 | a | 1 | | 2 | b | 1 | | 3 | c | 1 | | 4 | d | 2 | | 5 | e | 2 | | 6 | f | 3 | +----+------+-------+

category_count = [3,2,1]

What I did to get the count is,

if($model){
        $i = 0; $j = 0;
        $category_count = 0;
        $count [] = null;

        foreach($model as $question) {
            $category_count++;
            if(isset($output))
                if($question->catid != $output[$i-1]['cat'] ){
                    $count[$j] = $category_count;
                    $j++;
                    $category_count = 0;
                }
            $output[$i++] = ['id' => $question->id, 'cat' => $question->catid, 'title' => $question->title];
        }
        $count[$j]=$category_count;
        $final = ['count'=>$count, 'questions'=>$output];
}

My Question is,

  1. Instead of doing it in code can we get the count array using sql query efficiently.
  2. If not, help me in optimizing the code.

T!A.

Upvotes: 1

Views: 2379

Answers (2)

KTAnj
KTAnj

Reputation: 1356

SELECT ca.name, COUNT(*) 
  FROM questions qu
 INNER JOIN questions ca
    ON qu.catid = ca.id
 GROUP BY qu.catid

Upvotes: 0

marijnz0r
marijnz0r

Reputation: 934

Depending on the DDL of your tables, your query should look like this:

SELECT c.name, COUNT(*) 
FROM category c
JOIN questions q
ON q.catid = c.id
GROUP BY c.name

Upvotes: 2

Related Questions