如何根据角色获取名称

时间:2016-05-22 08:01:08

标签: sql sql-server

有没有办法根据角色在同一行显示两个人名。 我有4张桌子,这是人,学生,老师和TourAttend。人是两个表学生和老师的父母。

Person
-------
personID 
Name 
Role

Student 
--------
StudentID 
personID reference person

Teacher 
-------
teacherID
personID reference person

TourAttend
-----------
 TourID reference to Tour table (Which i didnt reveal)
 TourAttendID primary key
 PersonID  reference person

的示例值
 PersonID | Name    | Role
 -----------------------
     1    | student1| student
     2    | student2| student
     3    | teacher1| teacher
     4    | teacher2| teacher
     5    | student3| student

TourAttend的示例值

    TourID | tourAttend | PersonID 
       1   |    1       |    1 
       1   |    2       |    2
       1   |    3       |    3 
       2   |    4       |    4 
       2   |    5       |    5

我会得到一个查询结果,即每个学生都由谁(老师)陪同根据游览

 Student Name | Teacher Name 
   student 1  | teacher 1
   student 2  | teacher 1
   student 3  | teacher 2

到目前为止我只尝试了

    select person.name as 'student name' , person.name as 'Teacher name' from person

我被卡住了因为person.name被用于两者。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

这应该对你有用

select 
    t1.name as student_name, t2.name as teacher_name 
from
    (
        select
            p.name, t.TourID
        from 
            Person p
        inner join
            TourAttend t
        on
            p.PersonID = t.PersonID
        where
            p.role = 'student'
    ) t1
inner join
    (
        select 
            p1.name, t3.TourID
        from 
            Person p1
        inner join
            TourAttend t3
        on
            p1.PersonID = t3.PersonID
        where
            p1.role = 'teacher'
    ) t2
on
    t1.TourID = t2.TourID;