sql返回三次相同的列

时间:2014-02-03 21:18:21

标签: sql

我在尝试选择三次用户名时遇到了麻烦。

我有一张桌子

JOBS (id, id_student, id_professor, id_professor2) 

这最后一列是可选的,然后有时在其内容中设置NULL。发生这种情况时,查询不会返回任何行。但是,如果设置了id_professor2,则查询会像我期望的那样返回。我该如何解决这个问题?

SELECT 
    p.name as  professor, s.name as student, s_p.name as second_professor
FROM 
    users as p 
JOIN
    jobs ON (p.id = jobs.id_professor) 
JOIN 
    users as s ON (jobs.id_student = s.id) 
JOIN
    users as s_p ON (s_p.id = jobs.id_professor2)
WHERE 
    jobs.id = 2; 

id = 2的作业有第二位教授,因此查询正常运行。但是,如果jobs.id=3查询的更改未返回任何内容。

1 个答案:

答案 0 :(得分:1)

使用左外连接

SELECT p.name as  professor, a.name as student, s_p.name as second_professor
FROM  users as p
JOIN jobs ON(p.id = jobs.id_professor)
JOIN users as s ON(jobs.id_student = a.id)
left outer
JOIN users as c ON(c.id = jobs.id_professor2)
WHERE jobs.id = 2
;