mysql按分数/分数排名用户

时间:2012-11-15 07:56:36

标签: php mysql sql select

以下查询酷为正常用户按分数排名但我需要一个查询具有相同排名结果的相同分数表

SET @rank = 0;
SELECT * FROM (
    SELECT @rank:=@rank + 1 AS rank,score, user_id FROM site_crossword_members ORDER BY score DESC 
) as tmp; 

感谢

2 个答案:

答案 0 :(得分:2)

您确定您的查询甚至可以正常运行吗?我记得在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

答案 1 :(得分:2)

尝试此查询(带变量的版本) -

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;