1

两张表:

person(name,person_id)
lesson(teacher_id, student_id, time, place)

我要检索老师姓名、学生姓名、时间和地点

就像这样:

Teacher|Student|Time|Place
ms bla | fred  | 12 | UK
ms bla | Jim   | 12 | UK
mr ttt | john  | 10 | UNI

ETC..

那么如何选择person_id两次WHERE以匹配teacher-id& student_id

4

1 回答 1

5

您可以通过使用别名重命名表(DEMO )多次加入同一个表:

select
    teacher.name as Teacher,
    student.name as Student,
    lesson.time,
    lesson.place
from
    lesson
join
    person teacher on teacher.person_id = lesson.teacher_id
join
    person student on student.person_id = lesson.student_id

该表通过=lesson链接到person表(别名为teacher)。然后课程表通过=再次链接到表(这次别名为)。通过使用别名,我们可以引用每个别名的列来获取各自的教师和学生姓名。teacher_idperson_idpersonstudentstudent_idperson_idname

于 2013-03-18T23:41:37.307 回答