4个表中的Oracle SQL疯狂子查询

时间:2013-04-11 03:34:00

标签: sql oracle subquery

以下是关系:

CREATE TABLE employee (
  fname    varchar2(15) not null, 
  minit    varchar2(1),
  lname    varchar2(15) not null,
  ssn      char(9),
  bdate    date,
  address  varchar2(30),
  sex      char,
  salary   number(10,2),
  superssn char(9),
  dno      number(4),
  primary key (ssn),
  foreign key (superssn) references employee(ssn),
  foreign key (dno) references department(dnumber)
);

CREATE TABLE department (
  dname        varchar2(15) not null,
  dnumber      number(4),
  mgrssn       char(9) not null, 
  mgrstartdate date,
  primary key (dnumber),
  unique (dname),
  foreign key (mgrssn) references employee(ssn)
);

CREATE TABLE dept_locations (
  dnumber   number(4),
  dlocation varchar2(15), 
  primary key (dnumber,dlocation),
  foreign key (dnumber) references department(dnumber)
);

CREATE TABLE project (
  pname      varchar2(15) not null,
  pnumber    number(4),
  plocation  varchar2(15),
  dnum       number(4) not null,
  primary key (pnumber),
  unique (pname),
  foreign key (dnum) references department(dnumber)
);

CREATE TABLE works_on (
  essn   char(9),
  pno    number(4),
  hours  number(4,1),
  primary key (essn,pno),
  foreign key (essn) references employee(ssn),
  foreign key (pno) references project(pnumber)
);

问:找到至少在休斯顿工作的所有员工的姓名和地址,但他们的部门在休斯顿没有工作地点。

这是我的问题:

select fname, minit, lname, address
from employee
where dno=
(select dnumber from dept_locations where dlocation<>'Houston' and dnumber=
(select dno from employee where ssn=
(select essn from works_on where pno=
(select pnumber from project where plocation='Houston'))))

但它没有编译并返回此错误:

    ORA-01427: single-row subquery returns more than one row

请帮忙!

3 个答案:

答案 0 :(得分:0)

select fname, minit, lname, address
from employee
where dno in
(select dnumber from dept_locations where dlocation<>'Houston') and ssn in
(select essn from works_on where pno in
(select pnumber from project where plocation='Houston'))))

答案 1 :(得分:0)

您的电话“其中dno =”需要一个结果。

尝试

 where dno in (select...)

答案 2 :(得分:0)

select
  fname,
  minit,
  lname,
  address
from
  employee
where
  exists (
    select null
    from   works_on join project on (works_on.pno = project.pnumber)
    where  works_on.essn  = employee.ssn and
           not exists (
             select null
             from   dept_locations
             where  dept_locations.dlocation = project.plocation))

其他评论:

  1. 表和列命名缺乏一致性是非常恼人的。 DNO和DNUMBER?
  2. 使用社会安全号码作为键值是一个愚蠢的错误。这是愚蠢的,因为人们的SSN是私有的,应该受到保护,这是一个错误,因为它不是一成不变的。