Home > Mobile >  How to join three tables that are no so related
How to join three tables that are no so related

Time:07-28

I have three tables I want to join and hopefully, I don't confuse you.

The first table is the exam_students table

exam_students
|   id  |   student_id       | student_session_id  
|   1   |        20          |      1              
|   2   |        10          |      2              
|   3   |        21          |      3             
|   4   |        50          |      4              

The second table is the student_session table

student_session
|   id  |   student_id  | session_id  | class_id | section_id
|   1   |        20     |      12     |    2     |    1
|   2   |        10     |      12     |    2     |    1
|   3   |        21     |      12     |    1     |    2
|   4   |        50     |      12     |    4     |    1

The third one is the exam_results table

exam_results
|   id  |   exam_student_id | exam_subject_id | exam
|   1   |        1          |      12         |  55
|   2   |        2          |      14         |  76
|   3   |        3          |      9          |  45
|   4   |        4          |      3          |  87

what I want to get is the exam score of each student (from exam_results) based on the class_id, section_id and session_id from the student_session table.

I'm terribly new and bad at joining. I have gone through a few articles on joining but when I see this table, I don't even know how to begin. Please help me. How do I do this?

UPDATE

  1. student_session_id is gotten from the id in student_session table

  2. exam_student_id from the exam_results table is gotten from exam_students id

CodePudding user response:

Simply join all the tables, using the foreign keys as the joining criteria in each case.

SELECT *
FROM exam_students AS es
JOIN student_session AS ss ON es.student_session_id = ss.id
JOIN exam_results AS er ON er.exam_student_id = es.id
  • Related