I want find Students id that , must have (professorId = 3 And courseId = 4) And (professorId = 3 And courseId = 2) And (professorId = 5 And courseId = 8).
sometime these parenthesis is one or more than 20
I have two table class and studentsClasses like this :
studentsClasses table:
id | studentId | classId
1 1 2
2 1 3
3 1 4
4 2 3
5 2 5
6 3 2
7 4 3
8 4 2
9 1 8
Class Table:
id | professorId | CourseId
1 1 1
2 3 4
3 2 5
4 3 2
5 4 2
6 2 3
7 5 6
8 5 8
9 5 9
It would be very simple if every parenthesis worked as or. But I want to find a student who has all these things in the form of and.
This query is "OR" scenario:
select `studentsClasses`.`studentId` from `studentsClasses`
inner join `class` on (`studentsClasses`.`classId`=`class`.`id`
AND ((professorId = 3 And courseId = 4) OR (professorId = 3 And courseId = 2)
OR (professorId = 5 And courseId = 8)))
But i want AND scenario like this:
select `studentsClasses`.`studentId` from `studentsClasses`
inner join `class` on (`studentsClasses`.`classId`=`class`.`id`
AND ((professorId = 3 And courseId = 4) AND (professorId = 3 And courseId = 2)
AND (professorId = 5 And courseId = 8)))
But above query is wrong.
For example result query with these value should be :
studentId
---------
1
2
Answers
One way is to use CASE WHEN condition and SUM over it.
Another way is to use a separate join for each condition. Not an efficient solution, but it might be fine if data is not too big.
One option is to use IN operator on pair of columns, group by student HAVING Count() = Number of pairs listed – 3 in this sample and up to 20 or whatever it is in your actual context…
See the fiddle here.