Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all from one table and COUNT from another

Tags:

sql

select

mysql

K, so I have two tables:

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 |
+------------------+-------------+

I want to get all from categories and count the number of questions (question_id) on each category.

Say, the first category, billing, would have 1 question and the second one, security, would have 3 questions.

I've tried this:

SELECT categories.*, count(categories_questions.id) AS numberOfQuestions
FROM categories
INNER JOIN categories_questions
ON categories.id = categories_questions.category_id
like image 757
weare1 Avatar asked Dec 18 '25 16:12

weare1


1 Answers

You want to do this:

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

The LEFT JOIN will make sure that categories with no questions get listed with count = 0

like image 113
Adriano Carneiro Avatar answered Dec 20 '25 05:12

Adriano Carneiro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!