mysql 检索在由部门编号5控制的所有项目中工作的每个员工的姓名

svmlkihl  于 2023-03-07  发布在  Mysql
关注(0)|答案(5)|浏览(122)

这个问题摘自《数据库系统基础》第6版(Elmasri,Navathe)第5章查询3b。作者回答这个问题的一种方法是使用存在量词:

SELECT Lname, Fname
FROM EMPLOYEE
WHERE NOT EXISTS ( SELECT *
                  FROM WORKS_ON B
                  WHERE ( B.Pno IN ( SELECT Pnumber
                                    FROM PROJECT
                                    WHERE Dnum=5 )
                  AND
                  NOT EXISTS ( SELECT *
                               FROM WORKS_ON C
                               WHERE C.Essn=Ssn
                               AND C.Pno=B.Pno )));

作者将解决方案解释为:
选择每个员工,以便不存在该员工未参与的由部门5控制的项目
我不明白第二个内部相关子查询如何与其他不相关子查询和外部查询相关联以给出正确的结果。
任何帮助都很感激。

i7uq4tfw

i7uq4tfw1#

SELECT fname, lname FROM employee
WHERE NOT EXISTS
(SELECT pnumber FROM project WHERE dnum=5
AND pnumber NOT IN
(SELECT pno FROM works_on WHERE ssn=essn));

请注意Except在MySQL中不起作用

mm5n2pyu

mm5n2pyu2#

SELECT FNAME, LNAME
FROM EMPLOYEE 
WHERE NOT EXISTS 
((  SELECT PNUMBER 
        FROM PROJECT 
        WHERE DNUM = 5) 
     EXCEPT 
    (   SELECT PNO 
        FROM WORKS ON 
        WHERE ESSN = SSN));
qxsslcnc

qxsslcnc3#

我不得不修改查询,以便找到拥有Smith正在从事的所有项目的所有员工。因此,请按照编写的代码重新格式化:

SELECT fname, lname FROM employee
WHERE NOT EXISTS  --single EXISTS looking for Emp OUTER QUERY
(SELECT pnumber FROM project WHERE dnum=5  -- ALL Dept 5 Projects
    --add next line to exclude project 3 for dept 5 to return 2 employees (pNo 1&2)
    --AND EXISTS (SELECT * FROM WORKS_ON WHERE Pno=Pnumber and ESSN='123456789')
    AND pnumber NOT IN  -- with ea dept proj matching pno assigned to SSN·
    (SELECT pno FROM works_on WHERE ssn=essn)
);

添加注解的行将返回将部门5的所有项目(1,2)分配给Smith的所有员工,如果从项目中删除项目3,则输出相同。因此CONFUSION是NOT EXISTS,即返回所有记录不正确部门中的每个项目都不匹配。

ih99xse1

ih99xse14#

请尝试以下代码:

SELECT fname,
       lname
FROM   employee
WHERE  EXISTS(SELECT pnumber
              FROM   project
              WHERE  dnum = 5
                     AND pnumber IN (SELECT pno
                                     FROM   works_on
                                     WHERE  essn = ssn));
iklwldmw

iklwldmw5#

SELECT FNAME,LNAME
FROM   EMPLOYEE
WHERE  EXISTS   ( SELECT *
                  FROM DEPENDENT
                  WHERE SSN=ESSN)
AND EXISTS 
                ( SELECT *
                  FROM DEPARTMENT
                  WHERE SSN=MGR_SSN);

相关问题