我有一个包含三个表的模式:
项目( project_id ,proj_name,chief_arch)
员工( emp_id ,emp_name)
已分配( project_id,emp_id )
我已在http://sqlfiddle.com/#!9/3f21e上创建了包含数据的所有表格 您可以在http://sqlfiddle.com/#!9/3f21e/1上查看所有数据(选择* ...) 请先查看SQLFIDDLE上的表格和数据。
我有一个现有的查询来获取在至少一个项目上工作的员工姓名,员工107也在其中工作:
select EMP_NAME from employee natural join `assigned-to`
WHERE EMP_ID<>'107' AND
PROJECT_ID IN(
SELECT PROJECT_ID FROM `assigned-to`
WHERE EMP_ID='107'
)
GROUP BY EMP_NAME;
但现在我需要解决一个稍微不同的问题。我需要在员工107工作的所有项目上工作的员工姓名。
如何为此问题编写查询?
答案 0 :(得分:1)
试试这个:
SELECT EMP_NAME
FROM EMPLOYEE NATURAL JOIN `ASSIGNED-TO`
WHERE EMP_ID<>'107' AND
PROJECT_ID IN (
SELECT PROJECT_ID FROM `ASSIGNED-TO`
WHERE EMP_ID='107'
)
GROUP BY EMP_NAME
HAVING COUNT(*)=(
SELECT COUNT(*)
FROM `ASSIGNED-TO`
WHERE EMP_ID='107'
);
在SQL Fiddle上看到它。
答案 1 :(得分:0)
您可以通过计算与员工共同的其他员工的项目,然后仅选择计数与原始员工数量完全匹配的项目来实现此目的。
SELECT EMP_ID FROM `ASSIGNED-TO` WHERE PROJECT_ID IN
(SELECT PROJECT_ID FROM `ASSIGNED-TO` WHERE EMP_ID = '107')
AND EMP_ID <> '107'
GROUP BY EMP_ID
HAVING COUNT(*) = (SELECT COUNT(*) FROM `ASSIGNED-TO` WHERE EMP_ID = '107')
答案 2 :(得分:0)
这也会奏效。我想验证是否在项目表中找到了assign-to中的项目ID。
select e.emp_name
from employee e
natural join `assigned-to` a
where emp_id <> 107
and a.project_id in (
select project_id
from (
select emp_id, project_id
from employee natural join `assigned-to` natural join project
where emp_id = 107 ) t
)
group by e.emp_id
having count(project_id) = (select count(project_id) from `assigned-to` where emp_id = 107)