简体   繁体   中英

For ALL queries in SQL , Table division

I have a schema with three tables:

Project ( project_id ,proj_name,chief_arch)
Employee ( emp_id ,emp_name)
Assigned-to ( project_id,emp_id )

I have created all tables with data on http://sqlfiddle.com/#!9/3f21e
You can view the all data (select * ...) on http://sqlfiddle.com/#!9/3f21e/1
Please first view the tables and data on SQLFIDDLE.

I have an existing query to get employee names who work on at least one project where employee 107 also worked:

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

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.

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 .

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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