如何组合两个SQL查询,使一个查询的输出成为另一个查询的条件

时间:2017-04-15 04:01:39

标签: mysql sql postgresql

我有两个SQL查询

select a.name from Subjects a join Courses b on(a.id=b.subject) group by a.name having count(b.id) >=20;

这会返回20门或更多课程的科目名称。

select course from course_enrolments group by course having count(student)<20;

这将返回少于20名学生注册的课程。

如何将两个队列结合起来,以便我可以获得20个或更多课程和少于20个学生注册的科目名称?

Courses.id = Course_enrolment.course可用于加入表课程和课程表

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

试试这个:

select a.name 
from Subjects a join Courses b on(a.id=b.subject) 
where b.id in (select course
    from course_enrolments 
    group by course 
    having count(student)<20
)
group by a.name 
having count(b.id) >=20;

答案 1 :(得分:0)

试试这个:

SELECT
FROM (SELECT a.name,
        b.id as courseid
    FROM Subjects a
    JOIN Courses b
        ON a.id = b.subject
    GROUP BY a.name
    HAVING count(a.id) >= 20) s
JOIN (SELECT course
    FROM course_enrollments ce
    GROUP BY course
    HAVING count(*) < 20) c
ON c.course = s.courseid