This is a pretty basic question, but for some reason, I can’t reassure myself. I have a sql query that I want to ensure is acting as I expect.
question_records has a foreign key for both enrollments and questions
SELECT `question_records`.* FROM `question_records`
INNER JOIN `enrollments` ON `enrollments`.`id` = `question_records`.`enrollment_id`
INNER JOIN `questions` ON `questions`.`id` = `question_records`.`question_id`
WHERE (enrollments.id IN (10,20)
AND questions.id IN (500,600)
AND question_records.id not in (3000,4000))
What I want to make sure is that I will not get a question record with, for instance, an enrollment_id of 11 and a question_id of 500. In other words, does this inner join treat this where clause on a record-by record basis? More importantly, does it always treat it so? (I can come up with a test example, but want to make sure I’m not missing a case.
Edit: Additional narrative for clarity:
It is possible that there is a question_record in the database with an enrollment_id of 11 and a question_id of 500. If this query were not searching conditions on a record-by-record basis, it would match on the question_id of 500 and return the record. This is not the behavior that I want. I only want records for which both the enrollment_id and the question_id are matched for a given record. The answers I’ve gotten cover this condition.
A mental model for evaluating this query is that:
question_records,enrollments, andquestions.INNER JOINfilters the rows of the cartesian product this based on whether theONconditions are true.WHEREcondition.(Obviously the database will optimise that to something else entirely.)
So, if a row matches the
INNER JOIN..ONconditions, but does not match theWHEREone, it won’t appear in the final result. It has to match all the conditions.This might be easier to understand when you know that your
INNER JOINis equivalent to this:(This form matches the mental model I outlined better.)