2013-03-06 226 views
10

我有一個員工表和 培訓的另一個表。培訓表包含 員工已完成的各種培訓課程。我們有強制性的安全意識培訓,所以每個員工都必須完成這個培訓課程。我在運行查詢時遇到問題,這會返回所有員工列出的完成培訓或未完成的任務。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 

缺少「安全意識」類的員工沒有出現,而是落入裂縫中。

+1

是部門標識等於employee.id? – Maciej 2013-03-06 16:06:18

回答

10

使用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 

結果

╔════╦══════╦════════════════════╗ 
║ ID ║ NAME ║  CLASS  ║ 
╠════╬══════╬════════════════════╣ 
║ 1 ║ Bob ║ Security Awareness ║ 
║ 2 ║ Tom ║ Security Awareness ║ 
║ 3 ║ John ║ (null)    ║ 
╚════╩══════╩════════════════════╝ 
+3

非常酷,我不知道我可以在連接內過濾。這也將有助於其他領域。 – Rich 2013-03-06 16:36:33

+0

我在這裏有另一個解釋http://stackoverflow.com/a/15205900/491243 – 2013-03-06 16:38:53

1

你正在執行一個內部連接,你想要的是一個左外部連接。區別在於:內部連接將在處僅有結果,其中連接表中存在匹配。左外連接將返回主表中的所有結果,無論結合表中是否有結果。

+0

一點也不..不會工作 – 2013-03-06 15:51:44

0

你在找什麼叫做外部加入。在這種情況下,您需要左外連接:

SELECT employee.id, employee.name, training.class 
FROM employee LEFT OUTER JOIN training ON employee.id = training.department_id 
WHERE training.class LIKE '%Security%' 
ORDER BY employee_id 
0

而不是JOIN使用左外連接。我也想改變你的WHERE子句

WHERE training.Id = 1 

如果這相當於

0
Select e.id, e.name, t.class from employee e left outer join training t on e.id = t.department_id where t.class like '%Security%' order by e.id