【问题标题】:TROUBLE IN MULTIPLE SUBSELECT QUERY多个子选择查询中的问题
【发布时间】:2016-12-22 20:29:02
【问题描述】:

我需要找到与PETER具有相同功能或工资大于或等于SANDERS的所有员工的namefunctionofficenamesalary。按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')

我被这个查询卡住了。

【问题讨论】:

  • 你好 PM77-1,下一个查询如何?为“SANDERS”创建子选择?
  • @Rega,请务必勾选正确答案。

标签: sql oracle subquery multiple-tables


【解决方案1】:

假设这是 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 或其他东西,则必须稍微调整一下。

【讨论】:

    【解决方案2】:

    你需要在这里做三件事:
    1. 连接两个表,因为您需要两个表的结果
    2. 根据两个条件过滤结果
    3.排序结果:

    第一部分很简单,只需要根据officenumber加入即可:

    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
    

    【讨论】:

    • Nir - 我将编辑您的帖子以修正拼写错误(salery)并从表格别名中删除“as”。在 Oracle 中,不允许在表名与其别名之间使用“as”。您可以在列名(或用作列的表达式)和列别名之间使用“as”,这是一种很好的做法,但从来都不是必需的;但是对于表别名,这是不允许的。我看到当你写这篇文章时,数据库产品并不为人所知,但现在它是,而且它是 Oracle - 我正在编辑你的帖子,以供未来访问该线程的访问者使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    • 1970-01-01
    • 1970-01-01
    • 2012-05-08
    • 2014-12-07
    • 1970-01-01
    相关资源
    最近更新 更多