目录
?
?
?
SELECT DISTINCT Salary AS SecondHighestSalary ?
FROM Employee ?
ORDER BY Salary DESC ?
LIMIT 1 OFFSET 1;
SELECT DISTINCT Salary AS SecondHighestSalary
这部分是选择Salary
列,并且使用DISTINCT
关键字来确保结果中的薪水是唯一的。AS SecondHighestSalary
是给结果列一个别名,使结果集中的列名更易于理解。
FROM Employee ?
从 employee 表查询
ORDER BY Salary DESC ?
这部分是用来对Salary
列进行降序排序。这样,最高的薪水会被放在最前面。
LIMIT 1 OFFSET 1;
LIMIT 1 限制了结果集只返回一行,
OFFSET 1指定了跳过结果集中的第一行。
?
?
SELECT IFNULL(
(SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT 1 OFFSET 1),
NULL) AS SecondHighestSalary;
IFNULL(..., NULL)
: 这部分是用来处理子查询可能返回NULL的情况。如果子查询返回NULL,则整个查询结果也会是NULL;否则,结果会是子查询返回的值(即第二高的薪水)。
SELECT (SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT 1 OFFSET 1) AS SecondHighestSalary;