Printer
Printer

Reputation: 465

Mysql LEFT JOIN same table with WHERE condition

I've been trying to use LEFT JOIN to fetch student -> teacher and tutor. But it only returns one of them depending if the WHERE condition has p1.user_id = :userId or p2.user_id = :userId. But i would like to to fetch both the teacher and tutor based on the :userId

Students
ID | USER_ID | TEACHER_ID | TUTOR_ID |
1    5         3           4
Users
ID | FIRST_NAME| LAST_NAME | ROLE |
3    Lisa        Simpsons    TEACHER
4    Bart        Simpsons    TUTOR
5    Maggie      Simpsons    STUDENT

My Current query:

SELECT users.*
FROM users
LEFT JOIN students AS p1 ON users.id = p1.teacher_id
LEFT JOIN students AS p2 ON users.id = p2.tutor_id
WHERE p1.user_id = 5

Current result:

{id: 3, first_name: Lisa, last_name: Simpsons, role: TEACHER}

Expected Result

{id: 3, first_name: Lisa, last_name: Simpsons, role: TEACHER}
{id: 4, first_name: Bart, last_name: Simpsons, role: TUTOR}

Upvotes: 1

Views: 47

Answers (1)

ScaisEdge
ScaisEdge

Reputation: 133360

If you need left join you should not use left joined table column in where but add it to related on clause:

SELECT users.*
FROM users
LEFT JOIN students AS p1 ON users.id = p1.teacher_id AND p1.user_id = :userId
LEFT JOIN students AS p2 ON users.id = p2.tutor_id 

this way you get all the value in a row

SELECT s.*, u1.* ,u2.*
FROM student s
LEFT JOIN user  AS u1 ON u1.id = s.teacher_id
LEFT JOIN user  AS u2  ON u2.id = s.tutor_id
WHERE s.user_id = 5 

but if you want the result on different rows youn need union

select FIRST_NAME, LAST_NAME, ROLE
from student  
inner join  users on users.id = student.teacher_id 
    and student.user_id = 5
union 
select FIRST_NAME, LAST_NAME, ROLE
from student  
inner join  users on users.id = student.tutor:id 
    and student.user_id = 5

Upvotes: 3

Related Questions