查询前N名,第N名重复解决办法

需求:统计等级排名前N名,等级相同则比较经验值(基本上不会相同,除非到等级)
   如果第N名和第N+1名相同,则N+1名也输出,依此类推。

表信息:表名:players
        列名:playerID    玩家ID
              playerName  玩家名称
              level       等级
              exp         经验值

统计SQL:

### 确定结果肯定大于N的查询sql

SELECT p.`playerID`, p.`playerName`,p.`level`, p.`exp`
FROM `players` AS p, (SELECT t.`level` AS tLevel, t.`exp` AS tExp
                  FROM players AS t
                  ORDER BY t.`level` DESC,t.`exp` DESC
                  LIMIT N-1,1) AS t1
WHERE p.level >= t1.tLevel AND p.exp >= t1.tExp
ORDER BY p.level DESC,p.exp DESC;


### 不确定结果大小

SELECT p.`playerID`, p.`playerName`,p.`level`, p.`exp`
FROM `players` AS p,
(SELECT (CASE WHEN MIN(t2.ttLevel) IS NULL THEN 0 ELSE MIN(t2.ttLevel) END) AS tLevel
,(CASE WHEN MIN(t2.ttExp) IS NULL THEN 0 ELSE MIN(t2.ttExp) END) AS tExp
FROM (SELECT t.`level` AS ttLevel, t.`exp` AS ttExp FROM players AS t
ORDER BY t.`level` DESC,t.`exp` DESC
        LIMIT N) as t2
) AS t1
WHERE p.level >= t1.tLevel AND p.exp >= t1.tExp
ORDER BY p.level DESC,p.exp DESC;

你可能感兴趣的:(mysql)