数据库leetcode刷题

Posted Greenty_Q

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数据库leetcode刷题相关的知识,希望对你有一定的参考价值。

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

以上是关于数据库leetcode刷题的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode刷题笔记-数据结构-day16

LeetCode刷题笔记-数据结构-day5

LeetCode刷题笔记-数据结构-day20

LeetCode刷题笔记-数据结构-day12

LeetCode刷题笔记-数据结构-day12

LeetCode刷题笔记-数据结构-day9