I have three tables
1.) Students (id,firstName,Surname,email)
2.) Course_Student(student_id, course_id)
3.) Courses (id, name, classroom_id)
I need to select all students, which have count of curses more or equal = 3.
I contstruct this select and it seems that it works, but I am curious, if there will be more efective way to this select:
select
s.firstName, s.Surname
from
students s
inner join
course_student cs
on
s.id = cs.student_id
and
cs.course_id
in
(select
course_id
from
course_student
group by
course_id
having count(*) >= 3
);
2
Answers
You can make every
IN
clause into anINNER JOIN
Your current query selects all students who are on a course which has >= 3 students, but maybe that is what you want.
This query "select all students, which have count of curses more or equal = 3":
Make sure you index your junction table in both directions –
(course_id, student_id)
&(student_id, course_id)
.Here’s a db<>fiddle.