SQL:选择没有嵌套查询的查询

时间:2011-08-26 07:50:03

标签: sql nested

我有下一个输入数据, 有两个表

create table Courses(
id number(19) not null,
name varchar(100),
);

create table Students (
id number (19) not null,
name varchar(100),
course_id number (19) not null,
);

我需要编写查询以获取具有学生数量的所有cource,例如超过10 所以,我用这样的嵌套查询编写了变体

select distinct courses.name from student, courses where courses.id=student.courses_id and (select count(Students.id) from Students where student.course_id = course.id)  > 10 

!!!没有测试,只为这篇文章写的,这是例子!!! 所以,我的问题是如何在没有嵌套查询的情况下编写相同的查询?

2 个答案:

答案 0 :(得分:2)

使用GROUP BY / HAVING子句:

SELECT courses.name /*, COUNT(*)*/
FROM student JOIN courses ON courses.id = student.courses_id
GROUP BY courses.id
HAVING COUNT(*) > 10

答案 1 :(得分:2)

我会选择

Select c.name, count(s.id) as StudentsCount from Courses c join stundets S on c.id = s.course_id group by c.name having count(s.id) > 10