简体   繁体   中英

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}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM