我有3个表:项目,员工和 project_employee
雇员
项目
project_employee
我要做的是编写一个查询,获取项目中没有的所有员工的ID和名称,例如项目编号9.
所以我试过了:
SELECT ID, Name
FROM [employee], [project_employee]
WHERE [employee].ID != [project_employee].emp_id AND [project_employee].project_id = 9;
但我总是得到空洞的结果,我的逻辑肯定有问题吗?
答案 0 :(得分:2)
相反,尝试这样的事情,它应该让所有不属于project_id = 9
SELECT u.ID, u.Name
FROM [User] u
WHERE u.ID NOT IN (SELECT pe.employee_id
FROM [project_employee] pe
WHERE pe.project_id = 9);
答案 1 :(得分:2)
您可以使用LEFT JOIN
获取所需数据
select e.id,e.name
from employee e
left join project_employee pe
on e.id = pe.employee_id
left join projects p
on pe.project_id = p.project_id
where p.project_id is null
(或)刚刚与project_employee
表保持联系。假设没有项目的所有员工都是期望的输出,则没有检查任何条件。
select e.id,e.name
from employee e
left join project_employee pe
on e.id = pe.employee_id
where pe.project_id is null
答案 2 :(得分:2)
SELECT ID, NAME
FROM employee e
LEFT JOIN project_employee pe
ON pe.employee_id = e.id
AND pe.project_id = 9
WHERE pe.employee_id IS NULL
您甚至不需要项目表,因为您没有在项目中寻找员工。
答案 3 :(得分:2)
您可以使用NOT EXISTS
执行此操作:
SELECT u.ID, u.Name
FROM [User] u
WHERE NOT EXISTS ( SELECT *
FROM [project_employee] pe
WHERE pe.project_id = 9
AND pe.employee_id = u.ID);
答案 4 :(得分:1)
他要求检查员工是否在特定项目中。 不在解决方案中没问题,但我通常更喜欢使用左连接。
SELECT ID, NAME
FROM employee e
LEFT JOIN project_employee pe
ON pe.emp_id = e.id
and pe.project_id = 9
WHERE pe.employee_id IS NULL