让我说,我有两个表类别和问题。
在问题表中,我在同一类别下有几个或多个问题,并且该表有不同类别的问题。
我需要问题表下每个类别的行数。
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]
我要做的是,

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];
}

我的问题是,
我们可以使用sql查询来高效地获取count数组,而不是用代码来实现。
如果没有,请帮助我优化代码。
T!答。

最佳答案

根据表的DDL,查询应如下所示:

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

关于php - 获取MySQL表中每个类别的行数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30525020/

10-16 05:15
查看更多