【问题标题】:stuck on writing this nested subquery, confused by a step on joining table坚持编写这个嵌套子查询,被加入表的步骤弄糊涂了
【发布时间】:2015-11-30 17:00:48
【问题描述】:
Employee(fname, minit, lname, SSN, bdate, address, sex, salary, superssn, dno); fname,minit,lname is the employee's name; bdate is birth date; superssn is supervisor's social security #; dno is dept #
Department(dname, DNUMBER, mgrssn, mgrstartdate); mgrssn is manager ssn
Dept_locations(DNUMBER, DLOCATION); dlocation is department location
Project(Pname, PNUMBER, plocation, dnum)
Works_on(ESSN, PNO, hours); ESSN is employee ssn, pno is project number
Dependent(ESSN, DEPENDENT_NAME, sex, bdate, relationship)

我想列出所有不在项目 7 工作且位于底特律的经理的姓氏和名字、SSN

这看起来不错:

Select e.ssn, e.lname, e.fname
from employee e, department d
where (d.mgrssn = e.ssn)

where e.ssn NOT in (
        select w.essn
        from works_on w
        where w.pno = '07'
        and p.plocation = 'Detroit'
)

我想我需要在 pno = 07 之前放置一个 pno =works_on 联合声明,但有人告诉我我不需要它。所以我现在真的很困惑。

我还需要在括号中包含 where (d.mgrssn = e.ssn) 吗?

【问题讨论】:

  • 您不想要底特律的经理,还是想要底特律的经理?因为你不在排除底特律从事项目 7 的所有经理。
  • 我不想要底特律的经理。你能写一个答案吗,我会接受的

标签: sql database jointable nested-queries notin


【解决方案1】:

这是带有连接的长格式查询:

select e.ssn, e.lname, e.fname
from employee e
  join works_on wo on wo.ESSN = e.ssn
  join project PO on po.pnumber = wo.pno
  join dept_location dl on dl.dnumber = po.dnum
where dl.dlocation != 'Detroit'
  or po.pnumber != 7

如果你想避免大量的连接,这里是一个带有 not in 的查询:

select e.ssn, e.lname, e.fname
from employee e
where e.ssn not in
(select wo.essn from works_on wo
  join dept_locations dl on dnumber = wo.pno
  where dl.dlocation = 'Detroit'
    or po.pnumber = 7)

希望对您有所帮助。

【讨论】:

  • 也谢谢 有时候我看到用select的时候,人家只放lname ssn fname,没有e。在它面前。我需要那些吗?
  • 不,为了清楚起见,我只是把它们留在里面,因为在第一个选择中只有一个表,你不需要列名前面的表别名,因为没有歧义(即:由于只有一个表,因此在两个不同的表中不可能有两个列具有相同的名称)。子查询可能仍然需要它们,因为有可能在表之间共享列名。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 2019-01-12
  • 1970-01-01
  • 2014-08-14
  • 2016-02-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多