我有一个包含三个表的数据库。 “名册”,“培训课程”和“课程注册” 名册和课程注册通过“ETID”(员工培训ID)连接。课程注册和培训课程通过“课程ID”连接 我正在尝试创建一个将返回所有员工的查询,并为所有课程创建一个YES / NO值。 我写了以下内容来了解具体的员工,但我似乎无法找到返回所有员工的正确方法。任何帮助将不胜感激。
SELECT [TRAINING COURSES].[course id]
, [TRAINING COURSES].[course name]
, "YES" AS Completed
, [COURSE ENROLLMENT].[training date]
FROM [TRAINING COURSES]
INNER JOIN [COURSE ENROLLMENT]
ON [COURSE ENROLLMENT].[course id]=[TRAINING COURSES].[course id]
WHERE [COURSE ENROLLMENT].[ETID]=[ENTER ETID]
UNION ALL
SELECT [TRAINING COURSES].[course id]
, [TRAINING COURSES].[course name]
, "No" AS Completed
, NULL
FROM [TRAINING COURSES]
WHERE NOT EXISTS
(
SELECT *
FROM [COURSE ENROLLMENT]
WHERE [COURSE ENROLLMENT].[course id]=[TRAINING COURSES].[course id]
AND [COURSE ENROLLMENT].[ETID]=[ENTER ETID:]
)
ORDER BY [TRAINING COURSES].[course name];
答案 0 :(得分:3)
您不需要在此查询中使用Union。使用LEFT OUTER JOIN替换INNER JOIN,它将完成与查询相同的操作,但性能会更好。
SELECT [Training Courses].[Course Id], [Training Courses].[Course Name],
IIF(IsNull([Course Enrollment].[ETID]), "NO", "YES") as Completed,
[Course Enrollment].[Training Date]
FROM [Training Courses]
LEFT OUTER JOIN [Course Enrollment]
ON [Training Courses].[Course Id] = [Course Enrollment].[Course Id]
ORDER BY [Training Courses].[Course Name]
如果您想要所有员工和所有课程,您需要在名册和培训课程表之间进行交叉连接。然后,您将使用课程注册表进行左连接,以获得上面的“是”。
答案 1 :(得分:0)
从两个子查询中删除WHERE [COURSE ENROLLMENT].[ETID]=[ENTER ETID]
。