如何打印在硬件部门和软件部门工作的每个员工的姓名和年龄?

时间:2019-04-06 12:15:11

标签: sql database oracle

我写了这个查询,询问在硬件和软件部门工作的Employee的打印名称和年龄,但它没有给我正确的输出结果!!

create table emp1 
(
eID integer PRIMARY key ,
eNAME varchar2(30),
age integer ,
salary integer
);        
 create table works 
  (
  eID integer REFERENCES emp1(eID),
  dID integer REFERENCES dept(dID1),
  pct_time integer 
  );
 create table dept
(
dID1 integer UNIQUE,
dNAME VARCHAR2(30) ,
budget integer ,
managerID integer ,
PRIMARY key(dID1,managerID)
 );

select eNAME,age from emp1 , works where works.dID in(select dept.dID1 
from  dept where dNAME='Hardware');

2 个答案:

答案 0 :(得分:1)

一种方法是使用EXISTS和相关子查询来检查是否存在将员工映射到软件和硬件的记录。

SELECT e.ename,
       e.age
       FROM emp1 e
       WHERE EXISTS (SELECT *
                            FROM works w
                                 INNER JOIN dept d
                                            ON d.did1 = w.did
                            WHERE d.name = 'Software')
             AND EXISTS (SELECT *
                                FROM works w
                                     INNER JOIN dept d
                                                ON d.did1 = w.did
                                WHERE d.name = 'Hardware');

另一种方法是将部门加入员工,过滤软件或硬件,然后GROUP BY员工的属性。如果它们都可以使用,则不同部门ID的数量必须为2。可以在HAVING子句中进行检查。

SELECT e.name,
       e.age
       FROM emp1 e
            INNER JOIN works w
                       ON w.eid = e.eid
            INNER JOIN dept d
                       ON d.did1 = w.did
       WHERE d.dname IN ('Software',
                         'Hardware')
       GROUP BY e.ename,
                e.age
       HAVING count(DISTINCT d.did) = 2;

答案 1 :(得分:0)

SELECT E.ename, E.age 发件人 Emp E、Works W1、Works W2、Dept D1、Dept D2 WHERE E.eid = W1.eid AND W1.did = D1.did AND D1.dname = ‘Hardware’ AND E.eid = W2.eid AND W2.did = D2.did AND D2.dname = ‘软件’