开发者

SQL: Select query without nested query

I have next input data, There are two tables

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,
);

I need to write query for get all cources with count of student for example more than 10 So, I've written variant with nested query like this

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 

!!! Didn't test, just wrote for this post, it is example!!! So, My question is how to write the same query without nested query?


Use the GROUP BY/HAVING clause:

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


I would go with

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜