我有一個員工表和 培訓的另一個表。培訓表包含 員工已完成的各種培訓課程。我們有強制性的安全意識培訓,所以每個員工都必須完成這個培訓課程。我在運行查詢時遇到問題,這會返回所有員工列出的完成培訓或未完成的任務。SQL查詢一對多關係
例Employee表
╔════╦══════╗
║ ID ║ NAME ║
╠════╬══════╣
║ 1 ║ Bob ║
║ 2 ║ Tom ║
║ 3 ║ John ║
╚════╩══════╩
實例訓練表
╔════╦══════════════╦════════════════════╗
║ ID ║ DEPARTMENT_ID║ CLASS ║
╠════╬══════════════╬════════════════════╣
║ 1 ║ 1 ║ Security Awareness ║
║ 2 ║ 1 ║ Workplace Safety ║
║ 3 ║ 2 ║ Security Awareness ║
╚════╩══════════════╩════════════════════╝
目標結果
╔════╦══════╦════════════════════╗
║ ID ║ NAME ║ CLASS ║
╠════╬══════╬════════════════════╣
║ 1 ║ Bob ║ Security Awareness ║
║ 2 ║ Tom ║ Security Awareness ║
║ 3 ║ John ║ (null) ║
╚════╩══════╩════════════════════╝
,我使用的查詢是
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
缺少「安全意識」類的員工沒有出現,而是落入裂縫中。
是部門標識等於employee.id? – Maciej 2013-03-06 16:06:18