对于按分数排名的普通用户来说,下面的查询很酷,但我需要一个具有相同排名结果的查询,以获取表中相同的分数
SET @rank = 0;
SELECT * FROM (
SELECT @rank:=@rank + 1 AS rank,score, user_id FROM site_crossword_members ORDER BY score DESC
) as tmp;
谢谢
您确定您给定的查询甚至可以正常工作吗?我记得ORDER BY
要在 之后完成SELECT
,从而使您的等级排序ID ASC
或相似。
SELECT user_id,
CASE WHEN @score != score THEN @rank := @rank + 1 ELSE @rank END AS rank,
@score := score AS dummy_value
FROM ( SELECT score, user_id
FROM site_crossword_members,
(SELECT @rank := 0, @score := NULL) AS vars
ORDER BY score DESC) AS h
缩短版:
SELECT user_id,
@rank := @rank + (@score != score) AS rank,
@score := score AS dummy_value
FROM ( SELECT score, user_id
FROM site_crossword_members,
(SELECT @rank := 0, @score := NULL) AS vars
ORDER BY score DESC) AS h
试试这个查询(带变量的版本) -
SET @rank = 0;
SET @score = NULL;
SELECT
rank, score, user_id
FROM (
SELECT
score,
user_id,
IF(@score = score, @rank := @rank + 1, @rank := 1) AS rank,
@score := score
FROM site_crossword_members
ORDER BY score DESC
) t;