恢复:
- tbl.Class 中的多名教师
- tbl.Course 中的单身教师
- 结果应该为 tbl.Course 中的每条记录提供一个来自 tbl.Class 的教师
我的 SQL 解释:
DECLARE @class TABLE ([id] int, [teacher] nvarchar(20))
DECLARE @course TABLE ([id] int, [course] nvarchar(20), [teacher_course] nvarchar(20))
INSERT INTO @class ([id], [teacher]) VALUES (1, 'Teacher 1')
INSERT INTO @class ([id], [teacher]) VALUES (2, 'Teacher 2')
INSERT INTO @class ([id], [teacher]) VALUES (3, 'Teacher 3')
INSERT INTO @class ([id], [teacher]) VALUES (4, 'Teacher 4')
INSERT INTO @class ([id], [teacher]) VALUES (5, 'Teacher 1')
INSERT INTO @course ([id], [course], [teacher_course]) VALUES (1, 'Course 1', 'Teacher 1')
INSERT INTO @course ([id], [course], [teacher_course]) VALUES (2, 'Course 2', 'Teacher 4')
SELECT
[co].[id],
[co].[course],
[cl].[teacher]
FROM @course [co]
INNER JOIN @class [cl] ON [co].[teacher_course] = [cl].[teacher]
GROUP BY
[co].[id],
[co].[course],
[cl].[teacher]
结果是:
[id] [course] [teacher]
1 Course 1 Teacher 1
2 Course 2 Teacher 4