I want to run a query which grabs all courses. Each row (course) should also have a user_count.
Let me show my table structure real quick. I have two tables of relevance. This doesn’t show all the fields for these tables, just the relevant info.
COURSE
id
title
desc
USER_COURSE
id
user_id (fk)
course_id (fk)
My first stab at this was to create the following query:
SELECT course.title, course.desc, COUNT(*) as `user_count`
FROM (`course`)
JOIN `user_course` ON `user_course`.`course_id` = `course`.`id`
GROUP BY `user_course`.`user_id`
The problem with this query is that it will only show courses which has records in the user_course table. Pointers?
Key points:
count(*)should beCOUNT(user_course.user_id)as you are counting number of users per coursecourse.idas you are grouping the result on per course basis.See the query bellow.