I have this table:
+--------+---------+---------+
|subject | student | remark |
+--------+---------+---------+
| sub1 | stud1 | Pass |
+--------+---------+---------+
| sub2 | stud1 | Pass |
+--------+---------+---------+
Subjects sub1 and sub2 are prerequisites to another subject. I want to extract the student’s remark from those two prerequisite subject to see if he is qualified to enroll.
I currently have:
SELECT enrollees.student, students_db.lastname, students_db.firstname FROM enrollees, students_db WHERE
(remark = 'Pass' AND subj = 'sub1' AND subj = 'sub2')
AND enrollees.student = students_db.student_id
This query yields no result.
It’s because in your
WHEREcondition you’re wantingsubj='sub1'ANDsubj='sub2'simultaneously, which can never be possible.One way to do it is to JOIN the table with
subandmark(enrolees?). This is because the student has to pass BOTH sub1 and sub2 (as opposed to passing AT LEAST ONE, in which case you can useand subj IN ('sub1','sub2'):This ensures that the student passes both sub1 and sub2.
However, it’s a bit sucky – if you have 5 prerequisites, all necessary, you have to
JOINinenrollees5 times.One way you can get around this, is to SUM up the number of passes they got. Then you don’t have to JOIN:
This counts up how many of the required subjects (in this case, ‘sub1’ and ‘sub2’) the student has passed, and makes sure that is equal to 2 (since they have to have passed all subjects).
This has the advantage of you being able to put in as many prerequisite subjects as you want (provided all are required prerequisites) — you just have to list them in the
WHEREand change the total in theHAVING. The number of joins does not grow with the number of prerequisites.