Skip to content
Advertisement

Mysql how to connect 2 subqueries

I have this mysql code:

select 
    course, students
from
    (select 
         course_id, count(*) as students
     from 
         taughtby
     where 
         u in (select s_id from student where s_id = u)
     group by 
         course_id) as B;

select 
    course, professors
from
    (select 
         course_id, u_id, count(*) as professors
     from 
         taughtby
     where 
         u in (select p_id from professor where p_id = u)
     group by 
         course_id) as A

My code returns 2 different result set in mysql workbench.

Is there any way I can connect those 2 result sets?

Advertisement

Answer

You can use double join clause among three tables :

 select course_id, count(distinct p_id) as professors, count(distinct s_id) as students
   from taughtby
   left join professor on p_id = u_id
   left join student on s_id = u_id
  group by course_id

including distinct keyword.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement