博客
关于我
mysql的分类排名_mysql高低排名
阅读量:789 次
发布时间:2023-02-13

本文共 1693 字,大约阅读时间需要 5 分钟。

数据准备与排名计算

首先,我们需要准备一个数据表user_score来存储用户的得分信息。表结构如下:

CREATE TABLE user_score (id bigint(64) NOT NULL AUTO_INCREMENT,userId bigint(64) DEFAULT NULL,score double DEFAULT NULL,PRIMARY KEY (id)) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

接下来,我们插入一些测试数据:

insert into user_score (id, userId, score) values('1','1','1');insert into user_score (id, userId, score) values('2','2','20');insert into user_score (id, userId, score) values('3','3','20');insert into user_score (id, userId, score) values('4','4','60');insert into user_score (id, userId, score) values('5','5','90');insert into user_score (id, userId, score) values('6','6','100');insert into user_score (id, userId, score) values('7','7',NULL);

然后,我们可以通过查询来计算用户的排名。以下是一个常见的排名方法:

SELECT t1.*, @rank := @rank + 1 rankFROM (SELECT a.userId, a.scoreFROM user_score aORDER BY a.score DESC) t1,(SELECT @rank := 0) t2

这种方法会为每个用户授予一个基于分数的排名。需要注意的是,当分数相同时,排名会按照顺序依次递增。

如果需要区分相同分数的排名,我们可以使用CASE WHEN语句来实现:

SELECT t1.*, (CASEWHEN @score = t1.score THEN @rankWHEN @score := t1.score THEN @rank := @rank + 1WHEN @score = 0 OR @score IS NULL THEN @rank := @rank + 1END) rankFROM (SELECT userId, scoreFROM user_scoreORDER BY score DESC) t1,(SELECT @rank := 0, @score := NULL) t2

这种方法会为每个用户根据分数计算出独特的排名,确保相同分数的用户排名相同。

最后,如果需要更复杂的排名逻辑,比如根据某些临时变量来计算排名,我们可以使用以下查询:

SELECT b.userId, b.score, b.rankFROM (SELECT a.*, @index := @index + 1, @rank := (CASEWHEN @temp_view_count = a.score THEN @rankWHEN @temp_view_count := a.score THEN @indexWHEN @temp_view_count = 0 OR @temp_view_count IS NULL THEN @indexEND) rankFROM user_score aORDER BY a.score DESC) a,(SELECT @rank := 0, @rowtotal := NULL, @index := 0) r) b

这种查询方式允许我们根据特定条件计算排名,非常适合需要高度定制排名逻辑的场景。

转载地址:http://evdfk.baihongyu.com/

你可能感兴趣的文章
MySQL密码忘记,怎么办?
查看>>
mysql对同一张表进行查询和赋值更新
查看>>
mysql导入数据库出现:Incorrect string value: '\xE7\x82\xB9\xE9\x92\x9F' for column 'chinese' at row 1...
查看>>
mysql导入(ibd文件)
查看>>
Mysql工作笔记006---Mysql服务器磁盘爆满了_java.sql.SQLException: Error writing file ‘tmp/MYfXO41p‘
查看>>
mysql常用命令
查看>>
MySQL常用指令集
查看>>
mysql常用操作
查看>>
MySQL常用日期格式转换函数、字符串函数、聚合函数详
查看>>
MySQL常见错误分析与解决方法总结
查看>>
MySQL底层概述—2.InnoDB磁盘结构
查看>>
MySQL底层概述—3.InnoDB线程模型
查看>>
MySQL底层概述—5.InnoDB参数优化
查看>>
MySQL底层概述—6.索引原理
查看>>
MySQL底层概述—7.优化原则及慢查询
查看>>
MySQL底层概述—8.JOIN排序索引优化
查看>>
MySQL底层概述—9.ACID与事务
查看>>
Mysql建立中英文全文索引(mysql5.7以上)
查看>>
mysql建立索引的几大原则
查看>>
Mysql建表中的 “FEDERATED 引擎连接失败 - Server Name Doesn‘t Exist“ 解决方法
查看>>