Search code examples
sqljoininner-join

SQL Query (or Join) for 3 tables


first time asking a question on Stack Overflow... Amazing resource, but there's just one thing that's really baffling me as a newcomer to SQL.

I have three tables and I would like to obtain the names of all the Mentors who are linked to Bob's students.

Table 1: TEACHERS

================
ID     Name
================
1     Bob

Table 2: STUDENTS

===================================
STUDENT_ID     Name     TEACHER_ID
===================================
1              Jayne    1
2              Billy    5
3              Mark     2

Table 3: MENTOR_RELATIONSHIPS

==============================
ID     STUDENT_ID    MENTOR_ID
==============================
1      1             3
2      2             2
3      3             3

Table 4: MENTORS

=====================
MENTOR_ID     Name  
=====================
1            Sally
2            Gillian
3            Sean

I would like to run a query to find all of the mentors of Bob's students. So the mentors for all students with TEACHER_ID = 1

In this case Sean would be the result.

I know that it is something to do with Joins, or could I find this using a normal query??

Any help is much appreciated! Many thanks...


Solution

  • this should do the work

    select distinct m.name from students s
    inner join mentor_ralationships mr on mr.student_id=s.student_id
    inner join mentors m on m.mentoir_id=mr.mentor_id
    where s.teacher_id=1;