【LeetCode数据库】——第二高的薪水(176)

一、题目

编写一个 SQL 查询,获取 Employee表中第二高的薪水(Salary) 。

+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+

例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null

+---------------------+
| SecondHighestSalary |
+---------------------+
| 200                 |
+---------------------+

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/second-highest-salary

二、解答

1. 创建数据表

mysql> create table if not exists Employee(Id int, Salary int);
Query OK, 0 rows affected (0.00 sec)

mysql> desc Employee;
+--------+---------+------+-----+---------+-------+
| Field  | Type    | Null | Key | Default | Extra |
+--------+---------+------+-----+---------+-------+
| Id     | int(11) | YES  |     | NULL    |       |
| Salary | int(11) | YES  |     | NULL    |       |
+--------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> truncate table Employee;
Query OK, 0 rows affected (0.00 sec)

2. 插入示例数据

mysql> insert into Employee (Id, Salary) values ('1', '100');
Query OK, 1 row affected (0.00 sec)

mysql> insert into Employee (Id, Salary) values ('2', '200');
Query OK, 1 row affected (0.00 sec)

mysql> insert into Employee (Id, Salary) values ('3', '300');
Query OK, 1 row affected (0.00 sec)

mysql> select * from Employee;
+------+--------+
| Id   | Salary |
+------+--------+
|    1 |    100 |
|    2 |    200 |
|    3 |    300 |
+------+--------+
3 rows in set (0.00 sec)

3. 编写查询语句

3.1 解法一

解题思路:

  • 从题目第二高的字眼可知,此查询语句必然涉及排序;
  • 想要获取某查询结果的某位置数据,则可以考虑使用分页limit
mysql> select distinct 
    ->     Salary as SecondHighestSalary
    -> from
    ->     Employee
    -> order by Salary desc
    -> limit 1 offset 1
    -> ;
+---------------------+
| SecondHighestSalary |
+---------------------+
|                 200 |
+---------------------+
1 row in set (0.00 sec)

上述查询语句虽然可以查出第二高的雇员薪水,但是并不满足如果不存在第二高的薪水,那么查询应返回 null

下列查询语句是完善后的查询语句,可以满足题目的所有要求:

mysql> select 
    ->     (select distinct
    ->         Salary
    ->     from
    ->         Employee
    ->     order by Salary desc
    ->     limit 1 offset 1)
    ->     as SecondHighestSalary
    -> ;
+---------------------+
| SecondHighestSalary |
+---------------------+
|                200  |
+---------------------+
1 row in set (0.00 sec)

3.2 解法二

mysql> select max(Salary) as SecondHighestSalary
    -> from Employee
    -> where 
    -> Salary < (select max(Salary) from Employee)
    -> ;
+---------------------+
| SecondHighestSalary |
+---------------------+
|                 200 |
+---------------------+
1 row in set (0.00 sec)

猜你喜欢

转载自blog.csdn.net/weixin_37780776/article/details/107723090
今日推荐