MYSQL articles get the second-highest salary

topic:

Write a SQL query to get the Employee table in the second-highest salary (Salary).

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

Employee table above example, SQL queries should return 200 as the second-highest salary.

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

If the second-highest salary does not exist, then the query should return null.

 

Problem-solving approach:

select 
ifnull
(
    (select 
     distinct(Salary) 
     from Employee
     order by Salary desc
     limit 1,1
    ),null
) 
as SecondHighestSalary;

Problem-solving point:

1, when comparing the size of salary, salary go weight;

2, when the sorting order by value, from small to large, reverse desc sort order;

3, paging query, give chestnuts:

SELECT name
FROM students
ORDER BY score DESC
LIMIT 3 OFFSET 0;

The above query expressed LIMIT 3 OFFSET 0, the result set record number 0 from the start, to take up three. Note SQL record set in the index from zero.

If you want to query page 2, then we only need to "skip" the first three records, which is the result set from the beginning of the 3rd record inquiry, the OFFSET is set to 3,

In MySQL, LIMIT 3 OFFSET 6 may also be abbreviated LIMIT 6, 3.

4, when mysql query results does not exist, returns null. Because the subject of the request if the second-highest salary does not exist, then the query should return null. So, here you can use ifnull syntax:

IFNULL(expression, value)
IFNULL() 函数用于判断第一个表达式是否有结果集,如果没有结果集,则返回value值。

 

 

Published 85 original articles · won praise 6 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_42595012/article/details/104054046