思路:设置一个变量并赋值初始值,循环一次自增加1,从而实现排序
三种排序
1、将已经排好顺序的数据从头开始取出,每取一条自增加一;
2、当出现相同数据时,排名保持不变,此时需要再设置一个变量,用来记录上一个数据的值,跟当前数据的值进行对比,如果相同,则排名不变,不相同则排名自增加一;
3、当出现相同数据时,排名保持不变,保持不变的排名依旧占用一个位置。
1、创建一张表分数表
CREATE TABLE score (
id INT (11) NOT NULL auto_increment,
memberId VARCHAR(64) NOT NULL,
score DOUBLE(5,2) NOT NULL,
PRIMARY KEY(id)
)
2、添加数据
INSERT INTO score (memberId, score)
VALUES
(100, 50.5),
(101, 30.6),
(102, 20),
(103, 60.3),
(104, 80.8),
(105, 50.7),
(106, 70.9),
(107,20),
(108,80.8)
3、查询
1、一次排列
select score.*,@scoreNum :=@scoreNum+1 as scoreNum from score,(select @scoreNum :=0) init ORDER BY score DESC

2、数据相同,排名保持不变,一次排序
select score.*,case when @score = score then @scoreNum when @score := score then @scoreNum :=@scoreNum+1 when @score =0 then @scoreNum :=@scoreNum+1 END as scoreNum from score,(select @scoreNum :=0,@score :=NULL) init ORDER BY score DESC

3、数据相同,排名保持不变,且占有字符
select score.*,@scoreNum1 :=@scoreNum1+1,@scoreNum := case when @score = score then @scoreNum when @score := score then @scoreNum1 when @score =0 then @scoreNum1 END as scoreNum from score,(select @scoreNum :=0,@score :=NULL,@scoreNum1 :=0) init ORDER BY score DESC


8880

被折叠的 条评论
为什么被折叠?



