SQL多个外键引用同一张表

时间:2018-08-07 10:50:36

标签: sql sql-server foreign-keys

我有下表学生

Id  FirstName   LastName    State   Index   Year    Course1 Course2 Course3 Course4 Course5
622 Student622  LastName622 State17 62200   2   54  47  68  67  50
623 Student623  LastName623 State16 62300   3   17  99  37  99  32
624 Student624  LastName624 State2  62400   4   8   71  11  58  86
625 Student625  LastName625 State1  62500   2   39  75  33  77  17
626 Student626  LastName626 State15 62600   3   11  3   4   70  72
627 Student627  LastName627 State13 62700   2   84  77  65  62  76
628 Student628  LastName628 State13 62800   4   87  18  19  4   75
629 Student629  LastName629 State10 62900   2   96  67  14  97  31

课程1、2、3、4、5中的数字是外键值,它们引用以下课程表的ID:

Id  Name    ProfessorId
1   Course 1    8
2   Course 2    14
3   Course 3    4
4   Course 4    3
5   Course 5    6
6   Course 6    2
7   Course 7    14
8   Course 8    4
9   Course 9    5

如何编写脚本,以便在我执行而不是外键编号时有课程名称?有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您可以为每个课程ID左加入“课程”表。

SELECT 
s.Id, s.FirstName, s.LastName, s.State, s.[Index], s.[Year],
c1.Name as Course1Name,
c2.Name as Course2Name,
c3.Name as Course3Name,
c4.Name as Course4Name,
c5.Name as Course5Name  
FROM Student s
LEFT JOIN Courses c1 ON c1.Id = s.Course1
LEFT JOIN Courses c2 ON c2.Id = s.Course2
LEFT JOIN Courses c3 ON c3.Id = s.Course3
LEFT JOIN Courses c4 ON c4.Id = s.Course4
LEFT JOIN Courses c5 ON c5.Id = s.Course5

由于所有这些都是LEFT JOIN的,因此将返回所有Student的记录。
即使某些课程ID未被填写。