【sql学习】LeetCode之176. Second Highest Salary

Write a SQL query to get the second highest salary from the Employee table.

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

For example, given the above Employee table, the query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null.

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

别人的代码:

方法一

Runtime: 126 ms, faster than 82.15% of MySQL online submissions for Second Highest Salary.

Memory Usage: N/A

SELECT MAX(Salary) SecondHighestSalary 
FROM Employee 
WHERE Salary  < (SELECT MAX(Salary) FROM Employee);

查询出没有重复值的第二名,即假如最高的身高是10000,有几个人同时工资是10000,则查出工资小于10000的所有工资中的最高工资(也就是全体的第二大)    

意义:先查询出最高的值,然后查询所有小于该值中的最高值。

Using max() will return a NULL if the value doesn't exist. So there is no need to UNION a NULL. Of course, if the second highest value is guaranteed to exist, using LIMIT 1,1 will be the best answer.

 

方式二:

SELECT
	Salary SecondHighestSalary 
FROM
	Employee
GROUP BY
	Salary
ORDER BY
	Salary DESC
LIMIT 1 OFFSET 1

这种方式就是对于上面这种整张表只有一条记录的情况,通不过;

主要知识点: 
         a)limit的使用方法,limit n返回前n条记录limit n offest m从m+1条记录开始返回n条记录

         b)代码中使用group by Salary的作用是去重,对于大数据查询时使用group by去重比distinct的效率要高一些。

         c)LIMIT 1 OFFSET 1等价于写:limit 1,1

         d)LIMIT 1 OFFSET n-1,便是求出第n大数

 

Runtime: 142 ms, faster than 36.24% of MySQL online submissions for Second Highest Salary.

Memory Usage: N/A

select 
(select distinct salary
from Employee
order by salary DESC
limit 1 offset 1)
 as SecondHighestSalary;

          b)这里便是使用的distinct来进行去重

ps:

why 
(1) can handle null properly;
select (select distinct salary
from Employee
order by salary DESC
limit 1 offset 1) as SecondHighestSalary;

but (2) can not;
select distinct salary as SecondHighestSalary
from Employee
order by salary DESC
limit 1 offset 1;

interesting question, share my understanding after reading some posts. Query #2 (the inner layer of #1) returns the value as empty string "" (it is still a value though empty).
NULL, on the other hand is the absence of value or undefined. This happens when the outer layer select from an empty table throws NULL

简单理解就是:

(2)返回的是一个空集,但是空集不是NULL,

(1)如果对一个空集,进行select,就会返回NULL

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值