mysql 生成排名字段
2016-04-20 15:27
387 查看
假设有test表,下图为表机构和数据,score表示积分。现在要查询积分排名为第几的id??
查询语句
[sql] view plain copy
select id,score,(@rowno:=@rowno+1) as rowno from test,(select (@rowno:=0)) b order by score desc;
查询结果:
这样就得到了根据积分排名的位置了(rowno),要获得id只要在这个表的基础上进行查询就可以了
[sql] view plain copy
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 ;
查询语句
[sql] view plain copy
select id,score,(@rowno:=@rowno+1) as rowno from test,(select (@rowno:=0)) b order by score desc;
查询结果:
这样就得到了根据积分排名的位置了(rowno),要获得id只要在这个表的基础上进行查询就可以了
[sql] view plain copy
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 ;
相关文章推荐
- Mysql主从配置,实现读写分离
- mysql (master/slave)复制原理及配置
- Access denied for user 'mysql用户名'@'主机或IP' (using password: YES)'
- mysql存储过程
- MYSQL导入导出sql文件简析
- mysqli 预处理详解
- 解决MySQL Sending data导致查询很慢问题的方法与思路
- MySQL(一)
- 如何恢复MySQL主从数据一致性
- mysql不能启动:Unit mysql.service failed to load: No such file or directory的解决办法
- yum安装mysql,迅速上手
- jsp-MySQL连接池
- host ... is not allowed to connect to this MySql server 开放mysql远程连接
- MySQL 读写分离介绍及搭建
- MySQL 读写分离介绍及搭建
- 快速实现MySQL的部署以及一机多实例部署
- 查询分析mysqldumpslow
- MySQL的root密码忘记怎么办 修改root密码的方式
- mysql表大小写问题
- mysql 数据库备份