mysql求第N高数据

2020-07-20  本文已影响0人  尔东丶

SQL中查询第N高的数据

评分表ratings

方法一:如果求第二高的数据,运用子查询

步骤一:获取给定MovieId的所有rating

select * from ratings where MovieId=1111;

步骤二:运用distinct()进行去重

selcet distinct Rating from ratings where MovieId=1111;

步骤三:max()求出评分的最大值

select max(distinct Rating) from ratings where MovieId=1111);

步骤四:子查询,求出小于最大值的那个值

select max(distinct Rating) from ratings where MovieId=1111 and rating <(select max(distinct Rating) from ratings where MovieId=1111);

第二高值为4

方法二:如果求第N高,运用limit与offset

mysql里分页一般用limit来实现取2,3,4三条数据:

1. select* from ratings LIMIT 1,3

2.select * from ratings LIMIT 3 OFFSET 1

limit n表示查询结果返回前n条数据,offset n表示跳过n条语句

求第N高的评分:

select distinct Rating from ratings where MovieId=1111 order by Rating desc limit n,1;(注:n求的是第n+1高的数据)

上一篇 下一篇

猜你喜欢

热点阅读