I have a MySql database with three tables I need to combine in a query: schedule, enrolled and waitlist. They are implementing a basic class enrollment system.
Schedule contains the scheduled classes. When a user enrolls in a class, their user account id and the id of the scheduled class are stored in enrolled. If a class is at capacity, they are stored in waitlist instead. All three tables share a scheduleId column which identifies each class.
When I query the schedule table, I need to also return enrolled and waitlist columns that represent the number of users enrolled and waiting for that particular scheduleId.
A preliminary query I came up with to accomplish this was:
select s.id, s.classDate, s.instructor, COUNT(e.id) as enrolled from schedule as s left outer join enrolled as e on s.id = e.scheduleId group by s.id
which works ok for one or the other, but obviously I can’t get the values for both the enrolled and waitlist tables this way. Can anybody suggest a good way of doing this?
I would do it with another left join and two inline count(distincts)
When I ran this approach versus the subqueries it executed about twice as fast, but I am looking at a pretty small result set.