简体   繁体   English

Mysql LEFT JOIN 同一个表与 WHERE 条件

[英]Mysql LEFT JOIN same table with WHERE condition

I've been trying to use LEFT JOIN to fetch student -> teacher and tutor.我一直在尝试使用LEFT JOIN来获取学生 -> 老师和导师。 But it only returns one of them depending if the WHERE condition has p1.user_id =:userId or p2.user_id =:userId .但它只返回其中之一,具体取决于WHERE条件是否具有p1.user_id =:userIdp2.user_id =:userId But i would like to to fetch both the teacher and tutor based on the :userId但我想根据: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:如果您需要left join ,您不应该在where使用左连接表列,而是将其添加到相关on子句中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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