在多个副主题查询中发生故障

时间:2016-12-22 20:29:02

标签: sql oracle subquery multiple-tables

我需要找到与name功能相同或薪水更高的所有员工的functionofficenamesalaryPETER或等于SANDERS的工资。按functionsalary订购。

有两个表格:officeemployee

office包含:

officenumber

name

city

employee包含:

employeenumber
name
function
manager
sal
officenumber

这是我当前的SQL查询:

SELECT  NAME,
        FUNCTION,
        SAL
FROM    EMPLOYEE
WHERE   FUNCTIE   =   (SELECT     FUNCTION
                       FROM       EMPLOYEE
                       WHERE      NAME = 'PIETERS')

我坚持查询。

2 个答案:

答案 0 :(得分:3)

假设这是SQL Server(您从未指定过),那么这样的事情应该可行。

SELECT
    e.name,
    e.function,
    e.sal,
    o.name AS officename
FROM employee e 
    JOIN office o ON e.officenumber = o.officenumber
WHERE
    e.function = (SELECT function FROM employee WHERE name = 'PIETERS') OR
    e.sal >= (SELECT sal FROM employee WHERE name = 'SANDERS')
ORDER BY e.function, e.salary

如果你正在使用MySQL或其他东西,你必须稍微调整一下。

答案 1 :(得分:2)

你需要做的三件事:
1.加入两个表,因为你需要来自两个表的结果 2.根据两个标准过滤结果 3.订购结果:

第一部分很简单,只需要根据职业加入他们:

select e.name, e.function, o.name as officeName, e.salary from
  employee e inner join office o 
  on e.officenumber = o.officenumber

第二部分,简单的where子句:

  where e.function = (select function from employee where name = 'PETER') 
  or e.salary >= (select salary from employee where name = 'SANDERS')

和最后一个,订购:

  order by e.function, e.salary

全部放在一起:

select e.name, e.function, o.name as officeName, e.salary from
  employee e inner join office o 
  on e.officenumber = o.officenumber
  where e.function = (select function from employee where name = 'PETER') 
  or e.salary >= (select salary from employee where name = 'SANDERS')
  order by e.function, e.salary