标签:查询 -- 存在 分析 sql语句 code second class 作用
编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary) 。
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null。
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200 |
+---------------------+
select distinct salary from Employee order by salary desc limit 1,1 就可以,但是输不出null,所以外面再加一层 select (select distinct salary from Employee order by salary desc limit 1,1) as SecondHighestSalary ;
当Employee表里只有一条数据时,内层SQL语句查询不到数据,其返回结果是空,而外层SQL的作用是把内层的查询结果赋值给SecondHighestSalary.
select
(select distinct salary
from Employee
order by salary
desc limit 1,1)
as SecondHighestSalary ;
标签:查询 -- 存在 分析 sql语句 code second class 作用
原文地址:https://www.cnblogs.com/Tu9oh0st/p/10704604.html