当前位置: 移动技术网 > IT编程>数据库>Mysql > MYSQL实现排名及查询指定用户排名功能(并列排名功能)实例代码

MYSQL实现排名及查询指定用户排名功能(并列排名功能)实例代码

2018年11月05日  | 移动技术网IT编程  | 我要评论

前言

本文主要介绍了关于mysql实现排名及查询指定用户排名功能(并列排名功能)的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧

表结构:

create table test.testsort (
 
id int(11) not null auto_increment,
 
uid int(11) default 0 comment '用户id',
 
score decimal(10, 2) default 0.00 comment '分数',
 
primary key (id)
 
)
 
engine = innodb
 
auto_increment = 1
 
character set utf8
 
collate utf8_general_ci
 
comment = '测试排序'
 
row_format = dynamic;

思路:可以先排序,再对结果进行编号;也可以先查询结果,再排序编号。

说明:

@rownum := @rownum + 1 中 := 是赋值的作用,这句话的意思是先执行@rownum + 1,然后把值赋给@rownum;

(select @rownum := 0) r 这句话的意思是设置rownum字段的初始值为0,即编号从1开始。

实现排名:

方法一:

select t.*, @rownum := @rownum + 1 as rownum
 
from (select @rownum := 0) r, (select * from testsort order by score desc) as t;

方法二:

select t.*, @rownum := @rownum + 1 as rownum
 
from (select @rownum := 0) r, testsort as t
 
order by t.score desc;

结果:

 

查看指定用户排名:

方法一:

select b.* from
 
(
 
select t.*, @rownum := @rownum + 1 as rownum
 
from (select @rownum := 0) r,
 
(select * from testsort order by score desc) as t
 
) as b where b.uid = 222;

方法二:

select b.* from
 
(
 
select t.*, @rownum := @rownum + 1 as rownum
 
from (select @rownum := 0) r, testsort as t
 
order by t.score desc
 
) as b where b.uid = 222;

结果:

实现并列排名(相同分数排名相同):

select
 
obj.uid,
 
obj.score,
 
case
 
when @rowtotal = obj.score then
 
@rownum
 
when @rowtotal := obj.score then
 
@rownum :=@rownum + 1
 
when @rowtotal = 0 then
 
@rownum :=@rownum + 1
 
end as rownum
 
from
 
(
 
select
 
uid,
 
score
 
from
 
testsort
 
order by
 
score desc
 
) as obj,
 
(select @rownum := 0 ,@rowtotal := null) r

查询指定用户并列排名:

select total.* from
 
(select
 
obj.uid,
 
obj.score,
 
case
 
when @rowtotal = obj.score then
 
@rownum
 
when @rowtotal := obj.score then
 
@rownum :=@rownum + 1
 
when @rowtotal = 0 then
 
@rownum :=@rownum + 1
 
end as rownum
 
from
 
(
 
select
 
uid,
 
score
 
from
 
testsort
 
order by
 
score desc
 
) as obj,
 
(select @rownum := 0 ,@rowtotal := null) r) as total where total.uid = 222;

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网