mysql 生成排名字段

假设有test表,下图为表机构和数据,score表示积分。现在要查询积分排名为第几的id??

查询语句

[sql] view plain copy
 
  1. select id,score,(@rowno:=@rowno+1) as rowno from test,(select (@rowno:=0)) b order by score desc;  

查询结果:

这样就得到了根据积分排名的位置了(rowno),要获得id只要在这个表的基础上进行查询就可以了

 

[sql] view plain copy
 
  1. select id from (select id,score,(@rowno:=@rowno+1) as rowno from test,(select (@rowno:=0)) b order by score desc) c where rowno=1;  

rowno的值为你想要查询的名次,就得到对应的id了。

 

上面的rowno为1,排名第一的id就是2了

 

一行算这次拍名和上次排名的差:

 

select aa.id,aa.rowno, bb.rowno, aa.rowno-bb.rowno from
(SELECT * , (@rowno:=@rowno+1) as rowno FROM statisticsystem.report_live_hits a ,(select (@rowno:=0)) b order by duration) as aa,
(SELECT * , (@rowno1:=@rowno1+1) as rowno FROM statisticsystem.report_live_hits a ,(select (@rowno1:=0)) b order by users) as bb
where aa.main_id = bb.main_id and aa.cate_id=bb.cate_id and aa.sub_id=bb.sub_id and aa.root_id=bb.root_id ;

 

posted @   Bigben  阅读(1205)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示