LeetCode:Database 02.求第N高的薪水

要求:编写一个 SQL 查询,获取 Employee 表中第 n 高的薪水(Salary)。

表Employee:

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

例如上述 Employee 表,n = 2 时,应返回第二高的薪水 200。如果不存在第 n 高的薪水,那么查询应返回 null

+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| 200                    |
+------------------------+

分析:
1.首先需要求第n高的薪水,那么首先需要用到开窗函数dense_rank()进行一个排序
2.为了避免所求到的薪水重复,我们需要distinct去重
3.考虑到求取的结果要起一个别名"getNthHighestSalary(N)",我最先考虑到的是使用字符串拼接输出结果,但是缺少对应的函数N,后来查阅了下资料发现这里我们可以使用CREATE FUNCTION 语句创建自定义函数,下面是CREATE FUNCTION语句用法:

CREATE FUNCATION <函数名>  ( [ <参数1> <类型1> [ , <参数2> <类型2>] ] … )
RETURNS <类型>
BEGIN
RETURN (sql语句体); 
END

SQL语句:

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  RETURN (
      select distinct a.sl from(select salary as sl,dense_rank() over(order by salary desc)as r 
      from employee)a where a.r=N
  );
END

在mysql8.0以上版本创建自定义函数会遇到以下问题:
ERROR 1418 (HY000): This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled (you might want to use the less safe log_bin_trust_function_creators variable)
因为我们的bin-log日志没有开启

查看bin-log是否开启

show variables like 'log_bin_trust_function_creators';

解决方案:
1.我们需要在数据库中输入以下内容,

set global log_bin_trust_function_creators=1;

2.使用1的方法在计算机重启后失效,为了永久有效,需要在在my.cnf配置文件中添加:

log_bin_trust_function_creators=1

运行:

drop FUNCTION  if exists getNthHighestSalary;
DELIMITER //
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
    RETURN (
        select distinct a.sl from(select salary as sl,dense_rank() over(order by salary desc)as r
                                  from employee)a where a.r=N
    );
END//

DELIMITER  ;
SELECT  getNthHighestSalary(2);

版权声明:本文为qq_43713049原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。