在部门的所有项目中工作的员工

时间:2018-08-31 13:43:19

标签: mysql sql subquery

这是我的数据库:

  • 员工( id 部门ID ,姓名)
  • 部门( id ,姓名)
  • Project( id departament_id
  • 工作( employee_id,project_id

使用 PK FK (例如:员工具有部门的PK ID和FK departament_id(id))

我想选择在某个部门(例如,开发部门)的所有项目中工作的所有雇员(E.name)。

这是我的查询

 SELECT E.name, 
        COUNT(P.id) AS PW, 
        AVG(DISTINCT(Q.allproj)) AS PrjOfDep
   FROM Employee E 
   JOIN WORK W 
     ON W.employee_id= E.id
   JOIN Project P 
     ON P.id = W.project_id
   JOIN (SELECT D.id, 
                COUNT(P1.id) AS allproj 
           FROM Project P1
           JOIN Department D 
             ON P1.departament_id = D.id
            AND D.name = "Development" 
       GROUP BY D.id) Q ON P.departament_id = Q.id
       GROUP BY E.ID HAVING PW = PrjOfDep

这有点奏效,这是结果:

Name    PW  PrjOfDep    
Stark   2   2.0000
Mike    2   2.0000

我不知道如何检查Employee E工作的所有项目是否包括部门“开发”的所有项目,因此我做了一个花招,查询看起来很丑。我计算了E员工在开发部门工作的所有项目,并将其与部门“开发”的项目数进行了比较。

PrjOfDep是一个平均值,我做了这个丑陋的技巧,因为查询

SELECT E.name, 
       COUNT(P.id) AS PW 
  FROM Employee E 
  JOIN WORK W 
    ON W.employee_id = E.id
  JOIN Project P 
    ON P.id= W.project_id
  JOIN (SELECT D.id, 
               COUNT(P1.id) AS allproj 
  FROM Project P1 
  JOIN Department D 
    ON P1.departament_id= D.id
   AND D.name = "Development" 
   GROUP BY D.id) Q 
    ON P.departament_id= Q.id
   GROUP BY E.id HAVING PW = Q.allproj

给我错误:

 1054 - Unknown column 'Q.allproj' in 'having clause'

我想对我的问题进行更优雅的查询,并且我只想查看Employee的名称。谢谢!

2 个答案:

答案 0 :(得分:1)

您的尝试似乎比您要求的要多得多。如果您的问题只是如何

  

选择在某个部门的所有项目(例如,开发)中工作的所有员工(E.name)。

然后类似以下的内容应该起作用:

SELECT e.name
FROM Employee e
INNER JOIN Work w ON e.eid = w.eid
INNER JOIN Project p ON w.pid = p.pid
INNER JOIN Department d ON p.did = d.did
WHERE d.Deptname = "Development"
GROUP BY e.name
HAVING  COUNT(p.Projname) = (SELECT count(p.Projname)
                FROM Department d
                INNER JOIN Project p ON d.did = p.did
                WHERE d.Deptname = "Development") 

此演示:SQL Fiddle

答案 1 :(得分:0)

这是我的解决方法

SELECT
  EMP.*
FROM Employee EMP
JOIN Department DEP
ON 1 = 1
 AND DEP.did = EMP.did
WHERE 1 = 1
 AND DEP.Deptname = 'Development'
 AND EMP.eid NOT IN(    
  SELECT DISTINCT
    DEPEMP.eid
  FROM Employee DEPEMP
  JOIN Project PRO
  ON 1 = 1
   AND PRO.did = DEPEMP.did
  LEFT JOIN Work WRK
  ON 1 = 1
   AND WRK.eid = DEPEMP.eid
   AND WRK.pid = PRO.pid
  WHERE 1 = 1
   AND DEPEMP.did = DEP.did
   AND WRK.eid IS NULL
);

遗憾的是,解决方案并不那么优雅。 试试here