从一个表中获取所有内容,从另一个表中获取COUNT

wea*_*re1 3 mysql sql select

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 |
+------------------+-------------+
Run Code Online (Sandbox Code Playgroud)

我希望从类别中获取所有内容并计算每个类别的问题数(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
Run Code Online (Sandbox Code Playgroud)

Adr*_*iro 9

你想这样做:

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
Run Code Online (Sandbox Code Playgroud)

LEFT JOIN将确保没有问题的类别列在count = 0