In my MySQL database, I have three tables students
, classes
, courses
.
One class
has many students
.
One class
has many courses
.
The courses
table has one boolean field active
, and a string field name
.
So overall relationship is (sorry I am not sure how to better illustrate the relationship if it is not clear) :
students (many_to_one) classes (one_to_many) courses
I have a function in Ruby that accepts an array of strings argument for the course name
s:
def get_student_names_whose_courses_are(active_course_names)
# Run a raw SQL query for the result
end
I would like to write a raw SQL query to get the names of students
whose courses
(via class
) matches exactly the passed in argument course names and are active.
For example, if active_course_names
holds values ['foo','bar']
. Student-A has active courses 'foo','bar','etc', student-B has active courses 'foo' and 'bar'. The raw quesry should only return student-B, even though student-A also has the two courses active, the point is an exact matching.
What I tried is this:
select stu.name
from students stu
inner join classes clz ON clz.id = stu.class_id
inner join courses cour ON cour.class_id = clz.id AND cour.name in (#{active_course_names,join("','")})
where cour.active = true;
But with this, it returns both student-A and student-B for the example above. How to make the query so that it returns students that have exactly the active courses?