Skip to content

Commit 297d107

Browse files
committed
update README.md
1 parent b726d79 commit 297d107

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Second Highest Salary
2+
3+
## Problem
4+
Write a SQL query to get the second highest salary from the Employee table.
5+
```
6+
+----+--------+
7+
| Id | Salary |
8+
+----+--------+
9+
| 1 | 100 |
10+
| 2 | 200 |
11+
| 3 | 300 |
12+
+----+--------+
13+
```
14+
For example, given the above Employee table, the second highest salary is 200. If there is no second highest salary, then the query should return null.
15+
16+
## Solution 1
17+
18+
可以使用子查询的方式,即
19+
20+
```sql
21+
select max(Salary) as SecondHighestSalary from Employee where Salary < (select max(Salary) from Employee);
22+
```
23+
24+
这种方式更通用,但使用了子查询(不相关子查询),效率会低点。
25+
26+
## Solution 2
27+
28+
使用mysql特有`LIMIT``IFNULL`语法,下面简单介绍下:
29+
30+
### LIMIT
31+
32+
LIMIT可以限制select语句的输出行数,可以有一个参数或者两个参数。
33+
34+
如果只有一个参数,则表示限制的最大行数,如果不足最大行数,则输出所有行。
35+
36+
如果两个参数,前一个参数表示与第一行的偏移量,偏移量为0表示从第一行开始输出,第二个参数表示最大行数。如果偏移量超出行数范围,输出为空
37+
38+
39+
### IFNULL
40+
41+
两个参数,如果第一个参数为空集合,则输出第二个参数。
42+
43+
综合以上两个函数,可以实现为:
44+
45+
```sql
46+
select ifnull((select distinct Salary from Employee order by Salary desc limit 1,1), null) as SecondHighestSalary;
47+
```

database/SecondHighestSalary/solve.sql

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,7 @@ insert into Employee values(1, 100);
55
insert into Employee values(2, 200);
66
insert into Employee values(3, 300);
77
*/
8-
select max(Salary) from Employee where Salary < (select max(Salary) from Employee);
8+
/*
9+
select max(Salary) as SecondHighestSalary from Employee where Salary < (select max(Salary) from Employee);
10+
*/
11+
select ifnull((select distinct Salary from Employee order by Salary desc limit 1,1), null) as SecondHighestSalary;

0 commit comments

Comments
 (0)