好的,我有两个表:
categories
+----+----------+
| id | slug |
+----+----------+
| 1 | billing |
| 2 | security |
| 3 | people |
| 4 | privacy |
| 5 | messages |
+----+----------+
categories_questions
+------------------+-------------+
| id | question_id | category_id |
+------------------+-------------+
| 1 | 1 | 2 |
| 2 | 2 | 5 |
| 3 | 3 | 2 |
| 4 | 4 | 4 |
| 5 | 4 | 2 |
| 6 | 5 | 4 |
+------------------+-------------+
我希望获取所有类别并计算每个类别中问题数(question_id)。
例如,第一个类别billing有1个问题,第二个类别security有3个问题。
我尝试过以下方法:
SELECT categories.*, count(categories_questions.id) AS numberOfQuestions
FROM categories
INNER JOIN categories_questions
ON categories.id = categories_questions.category_id