mysql 排序后获取某一行的位置

与世无争的帅哥 提交于 2020-01-01 05:41:56

表test中现有数据

id score
1 10
2 5
3 15

 

 

 

 

执行sql

select id,score,(@rowno:=@rowno+1) as rowno from test,(select (@rowno:=0)) b order by score desc; 

 

获得如下结果

id score rowno
3 15 1
1 10 2
2 5 3

 

 

 

 

然后在此基础上查询某条记录的位置

select rowno from (select id,score,(@rowno:=@rowno+1) as rowno from test,(select (@rowno:=0)) b order by score desc) c where id = 1;

这样就可以查到id为1的记录的排序为2

 

 

 

 

 

 

参考: http://blog.csdn.net/sugang_ximi/article/details/6703804

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!