您的位置:首页 > 博客中心 > 数据库 >

【数据库】leetcode刷题

时间:2022-03-15 19:47

目录

176. 第二高的薪水 (limit, order by, ifnull)

技术图片

limit的用法:

  • limit y : 读取 y 条数据
  • limit x, y : 跳过 x 条数据,读取 y 条数据
  • limit y offset x : 跳过 x 条数据,读取 y 条数据

按照salary 从大到小排序:

  • order by salary desc

这里要求如果不存在第二大的就返回null:

  • ifnull(expression,value): 当expression获得数据为空的时候,返回value,否则返回expression获得的数据
# Write your MySQL query statement below
select ifnull((select distinct salary from Employee order by salary desc limit 1,1) , null) as SecondHighestSalary;

177 第N高的薪水(SQL函数)

技术图片

这个题思路和176一样,但是代码框架是给的SQL函数,把查询返回的结果当作函数的返回值

limit 的参数不能为表达式"N-1" 只能为具体的数字,所以必须先把N变成N-1,赋值语句前面需要加set

return 内的语句不能加分号,要在return末尾加括号

具体形式参看下面的代码

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  set N=N-1;
  RETURN (
       select ifnull((select distinct salary from Employee order by salary desc limit N ,1) , null)
  );
END

本类排行

今日推荐

热门手游