简体   繁体   English

对于SQL中的所有查询,表除法

[英]For ALL queries in SQL , Table division

I have a schema with three tables: 我有一个包含三个表的架构:

Project ( project_id ,proj_name,chief_arch) 专案project_id ,proj_name,chief_arch)
Employee ( emp_id ,emp_name) 员工emp_id ,emp_name)
Assigned-to ( project_id,emp_id ) 分配给project_id,emp_id

I have created all tables with data on http://sqlfiddle.com/#!9/3f21e 我已经在http://sqlfiddle.com/#!9/3f21e上使用数据创建了所有表
You can view the all data (select * ...) on http://sqlfiddle.com/#!9/3f21e/1 您可以在http://sqlfiddle.com/#!9/3f21e/1上查看所有数据(选择* ...)
Please first view the tables and data on SQLFIDDLE. 请首先在SQLFIDDLE上查看表和数据。

I have an existing query to get employee names who work on at least one project where employee 107 also worked: 我有一个现有查询,以获取在至少一个 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;  

SQLFiddle SQLFiddle

But now I need to solve a slightly different problem. 但是现在我需要解决一个稍微不同的问题。 I need the employee names who on work on ALL projects that employee 107 works on. 我需要在员工107从事的所有项目上工作的员工姓名。

How can I write a query for this problem? 如何为该问题编写查询?

Try this: 尝试这个:

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'
);

See it run on SQL Fiddle . 看到它在SQL Fiddle上运行。

You can do this by counting the projects other employees in common with the employee and then selecting only those where the count exactly matches the original employees count. 您可以通过对其他员工与该员工共有的项目进行计数,然后仅选择计数与原始员工计数完全匹配的项目来执行此操作。

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')

This will work too. 这也将起作用。 I want to validate if the project id in assigned-to is found in project table. 我想验证是否在项目表中找到了“分配给”中的项目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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM