我有一张这样的表:
id (PK) name teacher (FK) student (FK)
1 Ron 3 6
老师和学生都在另一张名为people
的表中。
people
id (PK) name age
3 Ali 42
6 Jon 12
我想执行查询以获取以下内容
name teacher's name student's name
Ron Ali Jon
这可能吗?我知道我可以执行两个单独的连接,但后来我有两行,并且没有指示哪个名称是教师,哪个是学生
答案 0 :(得分:12)
select t.name, p1.name teacher_name, p2.name student_name
from t
left join people p1 on (t.teacher=p1.id)
left join people p2 on (t.student=p2.id)
答案 1 :(得分:7)
试试这个:
SELECT a.name, b.name 'teacher name', c.name 'student name'
FROM mainTablle a
LEFT JOIN people b ON a.teacher = b.id
LEFT JOIN people c ON a.student = c.id
WHERE a.id = 1;