我说,我有两个表类别和问题。 在问题表中,我在同一类别下有几个或更多的问题,表格中有各种类别的问题。
我需要问题表下每个类别中的行数。
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];
}
我的问题是,
Ť!甲
答案 0 :(得分:2)
根据表格的DDL,您的查询应如下所示:
SELECT c.name, COUNT(*)
FROM category c
JOIN questions q
ON q.catid = c.id
GROUP BY c.name
答案 1 :(得分:0)
SELECT ca.name, COUNT(*)
FROM questions qu
INNER JOIN questions ca
ON qu.catid = ca.id
GROUP BY qu.catid