I would like to ask for help. I have 3 tables.
- students_name
- students_has_subjects
- subject
What is the sql statement to query 3 tables to display student_id, student_name, stud_subject where student is taken and the subject description.
I would like 2 type of display of records.
First display
1, Paul Mark, Math, Mathematics, Mathematics
1, Paul Mark, English, English Language
1, Paul Mark, Science, About Science
2, John Mark, Math, Mathematics, Mathematics
2, John Mark, English, English Language
2, John Mark, Science, About Science
Second display
1, Paul Mark, Math, English, Science
2, John Mark, Math, English, Science
Below is the 3 table sample and its records. thanks a lot.
students_name table
student_id, student_name
1, Paul Mark
2, John Mark
students_has_subjects
id, stud_name, stud_subject
1, Paul Mark, 1
2, Paul Mark, 2
3, Paul Mark, 3
4, John Mark, 1
5, John Mark, 2
6, John Mark, 3
Subjects
subject_id, subject_name, description
1, Math, Mathematics
2, English, English Language
3, Science, About Science
You have to use 2 joins to link these 3 tables.
INNER JOIN means, that only those tuples are listed, for which an correct tuple exists in every table. Students without subjects or wrong subject_ids will not be listed.
Keep in mind, that an student, which visits X subjects will also listed X times.
SELECT n.student_id, n.student_name, s.subject_name, s.description FROM student_name n INNER JOIN student_has_subjects shs ON shs.stud_name = n.student_name INNER JOIN subjects s ON shs.stud_subject = s.subject_idIf it is an homework of you, please mark it as one!