SQL:使用多个SELECT语句/检索两次相同的字段?

时间:2013-03-18 23:37:03

标签: mysql sql database

两张桌子:

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

等。

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

1 个答案:

答案 0 :(得分:5)

您可以使用alias重命名该表(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 = teacherteacher_id表(别名为person_id)相关联。然后,课程表再次person = studentstudent_id表格相关联(此次为person_id别名)。通过使用别名,我们可以为每个别名引用列name以获取相应的教师和学生姓名。