从三个表中选择

时间:2015-08-14 12:34:37

标签: mysql sqlite

我有一个关于从三个表中选择数据的问题 第一个表是这样的:Timetable

ClassID   teacherID   assistantID    
1           1            2
0                    
2            3            4

`0是休息时间,所以没有助手和老师

Class表:

classID     classname    
0            Break    
1            MATH    
2            ART

teacher

teacherID     teacherName    
1               Tom    
2               Lily    
3               Rose    
4               Nile

我想制作一个这样的表格 Timetables

ClassName      TeacherName     AssistantName    
Math            Tom            Liky    
Break                  
Art             Rose            Nile

1 个答案:

答案 0 :(得分:1)

使用不同的别名

加入teacher表两次
select c.className, teach.teacherName, assist.teacherName as assistantName
from Timetable t
join class c on c.classID = t.classID 
left join teacher teach on teach.teacherID = t.teacherID 
left join teacher assist on assist.teacherID = t.assistantID