在 SQL 中使用最大结果作为谓词的值

shi*_*zou 3 syntax

假设我想找到收入比 Google 的所有员工都多的所有员工,是否可以将 max 的结果用作单个值而不是像这样的表?

select person-name
from Works
where salary > ( select max(salary)
        from Works
        where company-name == "Google" )
Run Code Online (Sandbox Code Playgroud)

(作品有人名、薪水和公司名列)

a_h*_*ame 9

是的,这是可能的。但是,您的查询有几个语法错误。

  1. 标识符中的破折号无效。我在下面的示例中使用了下划线。如果您确实以这种方式创建了列,则需要引用它们,例如"person-name"
  2. SQL 中的相等运算符是=, 不是==
  3. 字符串常量需要放在单引号 ( ') 中,而不是双引号中

可以将 max 子查询的结果用作单个值,因为它是单个值。准确地说,它是一个子查询,因为max()返回单列和单行。

select person_name
from Works
where salary > (select max(salary)
                from Works
                where company_name = 'Google');
Run Code Online (Sandbox Code Playgroud)

您可以使用替代方法 with> ALL而不是>,使用没有聚合函数并返回许多值(许多行但仍然是单列)的子查询:

select person_name
from Works
where salary > ALL (select salary
                    from Works
                    where company_name = 'Google'
                      and salary is not null );
Run Code Online (Sandbox Code Playgroud)

请注意salary is not null第二个查询中的条件。必须从比较中取出空值,因为它们中的每一个都会将>操作评估为unknown而不是truefalse,因此整个> ALL条件结果将是未知的,并且您不会在输出中得到任何行。