Summary of Leetcode-Mysql topics and knowledge points (176. The second highest salary)

Computer Xiaobai QAQ, because I want to find a few summer internships, I have filled the members and want to focus on the mysql part of leetcode. Write this series of blog posts to communicate with you, and we will continue to update some of the prepared questions in the future. Welcome to communicate with you, and ask the big guys to spray QAQ. Because I have taken many detours as a beginner, I will try my best to write in detail. If you can help future friends, please leave a message to encourage me. Hahahaha.

176. The second highest salary

This question, after I roughly understand the general usage of the SQL language, has two ideas to share with you, and some knowledge points will be interspersed in the middle.

Idea 1: We can find the largest salary first, and then find the largest and second largest among all items smaller than the largest. The main knowledge points involved in this idea are the max function and where condition filtering. This is relatively simple and should be written out and everyone can understand.

Code:

select max(salary) SecondHighestSalary

from Employee

where salary<(select max(salary) from Employee)

Idea 2: Use the idea of ​​sorting (Actually, my first reaction was the window function row_number, but after thinking about it, order can be solved, so I won't talk about the window function here, I will introduce it in detail later)

Knowledge points: 1. Order by followed by the basis for sorting, by default it is in ascending order, after adding the desc keyword, it is changed to descending order

2. Distinct is to de-duplicate, for example, if 100, 100, 50 is not used, the sort result returned by distinct is 100, 100, 50, but in many cases we don’t want to consider the issue of parallel ranking, so we should use distinct to de-duplicate to reach 100, 50 sort effect

3. The limit is to limit the output. If it is the limit number N format, it means the first N of the sorting result is output. If it is the limit n, m format, it means that the output is the nth and the next m of the sorting result, not including n, for example, limit 1,1 in this question means that the first output after the first number is the second one.

4. Ifnull is the usage in mysql, mssql uses isnull, ifnull(x,y) means that if x is not empty, return x, otherwise return y. If there is no second highest salary in this question, it will Return directly to the empty space. In order to meet the requirements of the problem, another layer must be placed outside.

 select ifnull((select distinct salary 

from Employee

order by salary desc

limit 1,1),null)as SecondHighestSalary

 

Guess you like

Origin blog.csdn.net/weixin_43167461/article/details/113104312