小编典典

从一个表中获取全部,从另一个表中获取COUNT

sql

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)。

假设,第一个类别(计费)将有一个问题,第二个类别(安全)将有3个问题。

我已经试过了:

SELECT categories.*, count(categories_questions.id) AS numberOfQuestions
FROM categories
INNER JOIN categories_questions
ON categories.id = categories_questions.category_id

阅读 197

收藏
2021-03-08

共1个答案

小编典典

您想这样做:

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将确保没有问题类别获得与数= 0上市

2021-03-08