I have this simply query that returns 100 rows, each row is for 1 course:
select c.*
from courses c
join schools s ON s.id = c.school_id
How can I get the # of students who’s favorited the course, if I try this:
select c.*, st.id
from courses c
join schools s ON s.id = c.school_id
join students st ON st.favorite_course_id = c.id
In the above query, if I had say 100 courses, I will get many more results back since I am joining with the students table that has 1000’s of records.
I still want to get back 100 results, 1 row for each course, but I want to know the total # of students who have favourited a particular course.
2
Answers
You can use lateral join like the below :
Use a subquery instead of a join: