12

我有一张这样的桌子:

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

这可能吗?我知道我可以执行两个单独的连接,但是我只剩下两行,没有迹象表明哪个名字是老师,哪个是学生

4

2 回答 2

18
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)
于 2012-12-19T08:43:34.380 回答
8

试试这个:

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;
于 2012-12-19T08:44:45.213 回答