SQL查询一对多的关系

Ric*_*ich 15 sql join

我有一个Employees表和另一个Training表.培训表包含员工已完成的各种培训课程.我们有强制性的安全意识培训,因此每位员工都必须完成此培训课程.我在运行查询时遇到问题,该查询将返回列出完成培训的所有员工.

示例员工表

?????????????
? ID ? NAME ?
?????????????
?  1 ? Bob  ?
?  2 ? Tom  ?
?  3 ? John ?
?????????????
Run Code Online (Sandbox Code Playgroud)

示例培训表

??????????????????????????????????????????
? ID ? DEPARTMENT_ID?       CLASS        ?
??????????????????????????????????????????
?  1 ?           1  ? Security Awareness ?
?  2 ?           1  ? Workplace Safety   ?
?  3 ?           2  ? Security Awareness ?
??????????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)

目标结果

??????????????????????????????????
? ID ? NAME ?       CLASS        ?
??????????????????????????????????
?  1 ? Bob  ? Security Awareness ?
?  2 ? Tom  ? Security Awareness ?
?  3 ? John ? (null)             ?
??????????????????????????????????
Run Code Online (Sandbox Code Playgroud)

我正在使用的查询是

SELECT employee.id, employee.name, training.class
FROM employee
JOIN training ON employee.id = training.department_id
WHERE training.class LIKE '%SECURITY%'
ORDER BY employee_id
Run Code Online (Sandbox Code Playgroud)

错过"安全意识"课程的员工似乎没有出现,并且陷入了困境.

Joh*_*Woo 16

LEFT JOIN在表的连接过程中使用和移动过滤条件(特别是在ON子句中)

另一个问题是使用单引号:' '不是‘ ’

SELECT  employee.id, 
        employee.name, training.class
FROM    employee   
        LEFT JOIN training 
            ON employee.id = training.department_id AND
                training.class LIKE '%SECURITY%'
ORDER   BY employee.id
Run Code Online (Sandbox Code Playgroud)

结果

??????????????????????????????????
? ID ? NAME ?       CLASS        ?
??????????????????????????????????
?  1 ? Bob  ? Security Awareness ?
?  2 ? Tom  ? Security Awareness ?
?  3 ? John ? (null)             ?
??????????????????????????????????
Run Code Online (Sandbox Code Playgroud)

  • 很酷,我不知道我可以在加入中过滤.这也有助于其他领域. (3认同)