您的位置:首页 > 大数据

mysql 查询数据库中第n大数据的值

2017-05-04 14:47 225 查看
Write a SQL query to get the nth highest salary from the
Employee
table.
+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+


For example, given the above Employee table, the nth highest salary where n = 2 is
200
.
If there is no nth highest salary, then the query should return
null
.

答案:
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT

BEGIN

declare m int;

set m=n-1;

RETURN (

# Write your MySQL query statement below.

select distinct Salary from Employee order by salary desc limit m,1

);

END

limit函数 :
一个参数(10):检索前10个数据
两个参数(8,10):检索第8个数据,查询出十个

1、offset比较小的时候。

select * from yanxue8_visit limit 10,10

多次运行,时间保持在0.0004-0.0005之间

Select * From yanxue8_visit Where vid >=(

Select vid From yanxue8_visit Order By vid limit 10,1

) limit 10

多次运行,时间保持在0.0005-0.0006之间,主要是0.0006

结论:偏移offset较小的时候,直接使用limit较优。这个显示是子查询的原因。

2、offset大的时候。

select * from yanxue8_visit limit 10000,10

多次运行,时间保持在0.0187左右

Select * From yanxue8_visit Where vid >=(

Select vid From yanxue8_visit Order By vid limit 10000,1

) limit 10

多次运行,时间保持在0.0061左右,只有前者的1/3。

可以预先offset越大,后者越优。

mysql> SELECT * FROM table LIMIT 95,-1; // 检索记录行 96-last.

//如果只给定一个参数,它表示返回最大的记录行数目
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mysql