如何在具有不同条件的单个表上连接在同一列上运行的两个SELECT语句?

时间:2017-10-30 14:54:02

标签: sql oracle select

我正在尝试完成以下练习

  

创建一个查询,其中包含在' Research'中工作的每位员工的员工姓名,主管姓名和员工薪水。系

以下架构运作:

https://scontent-lht6-1.xx.fbcdn.net/v/t34.0-12/23140228_10214571052854224_1441212020_n.png?oh=15f361ec2679373f2cfeb427dd5b6978&oe=59F9593B

我已经开发了以下查询,它在某种程度上有效,但是没有相应地匹配行,因此我最终得到的结果包括员工姓名和工资,以及管理员名称的单独行。我的查询如下:

CREATE VIEW research AS
SELECT NULL as Fname, NULL as Lname, NULL as Salary, Lname as Manager from EMPLOYEE
WHERE Ssn IN (SELECT Superssn from EMPLOYEE WHERE Dno = (SELECT Dnumber from DEPARTMENT WHERE Dname = 'Research'))
UNION
SELECT Fname, Lname, Salary, Null as Manager  FROM EMPLOYEE
WHERE Dno = (SELECT Dnumber from DEPARTMENT WHERE Dname = 'Research');

有人能看出这有什么问题吗?我是否通过UNION命令正确使用它?

谢谢。

2 个答案:

答案 0 :(得分:3)

这似乎是你正在努力实现的目标。

select
    emp.FName       as EmployeeFName
    ,emp.LName      as EmployeeLName
    ,sup.FName      as SupervisorFName
    ,sup.LName      as SupervisorLName
    ,emp.Salary     as Salary

from
    Employee emp
    inner join  Department dept
            on  emp.dno = dept.dnumber
    inner join  Employee sup
            on  emp.SuperSSN = sup.SSN

where
    dept.Name = 'Research'

答案 1 :(得分:1)

不,你不想要UNION。

为什么您在员工身上有super_ssn,在DEPARTMENT上也有mgr_ssn?这不是多余的吗?

无论如何,这是另一种方法。

select fname, lname, salary, 
    (select lname from employee e where e.ssn = employee.superssn) manager
from employee
where dno = (SELECT Dnumber from DEPARTMENT WHERE Dname = 'Research');