Skip to content
Advertisement

How to fetch all recordsets which are linked through that table?

I have three tables, with these fields:

classes: class_id | name | grade

classes_students: class_id | student_id

students: student_id | name

Classes has a 1:n relationship with Students, so one class can have many students. I want to select all students of a particular class, where class_id is 5.

Could I just do something like this?

I’m not sure about if I need the join here and if that has to be a “LEFT JOIN”? What I want is only a record set containing the student names.

Advertisement

Answer

Use:

Alternately:

Because you want students only in a particular class, you’d use an INNER JOIN. You’d use a LEFT JOIN if you wanted say a list of all the students, and then LEFT JOIN to CLASSES_STUDENTS to know if any are taking classes (because those that aren’t would have null values in the CLASSES_STUDENTS columns). I recommend looking at this link for the breakdown of various JOINs and their impact on the data you’ll get back.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement