K,所以我有两个表:
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)。
例如,第一个类别(计费)有 1 个问题,第二个类别(安全)有 3 个问题。
我已经试过了:
SELECT categories.*, count(categories_questions.id) AS numberOfQuestions
FROM categories
INNER JOIN categories_questions
ON categories.id = categories_questions.category_id
最佳答案
你想这样做:
SELECT categories.id, max(categories.slug), count(categories_questions.id) AS numberOfQuestions
FROM categories
LEFT JOIN categories_questions
ON categories.id = categories_questions.category_id
group by categories.id
LEFT JOIN
将确保没有问题的类别以 count = 0 列出
关于mysql - 从一个表中获取全部并从另一个表中获取 COUNT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5984222/