2

私は次のランキングシステムを持っています。

SET @1=0;

SELECT id, username, magic_xp, @i:=@i+1 AS rank
  FROM hs_users
 ORDER 
    BY magic_xp DESC;

hs_users
id  username     magic_xp rank
988 5hapescape   14926854    1
737 Ozan         13034431    2
989 Kurt         13034431    3
  6 LEGACY              0    4
 11 Bobby               0    5
276 Bobby123            0    6
345 Mynamesjason        0    7
450 Demon Spawn         0    8
987 Satan               0    9

ご覧のとおり、2 人のユーザーが同じ XP を持っています。

私はそれらの両方を持たせたいと思ってrank = 2おり、残りはから従うべき3です。

どうすればこのようにグループ化できますか?

|  username  | magic_xp | rank |
| ---------- + -------- + ---- |
| ShapeScape |     1000 |    1 |
| Kurt       |      100 |    2 |
| Ozan       |      100 |    2 |
| Legacy     |       10 |    3 |
4

4 に答える 4

3

MySQL で最も効率的な方法は、変数を使用することです。

  select t.*,
         (@rank := if(@magic_xp = magic_xp, @rank,
                      if(@magic_xp := magic_xp, @rank + 1, @rank + 1)
                     )
         ) as rank
  from table t cross join
       (select @rank := 0, @magic_xp := NULL) params
  order by magic_xp desc;

変数の複雑な式に注意してください。両方の変数の割り当ては、1 つの式で行われます。これはわざとです。MySQL は、 a での式の割り当ての順序を保証せずSELECT、場合によっては、それらを順番に評価することさえしません。単一の式は、このロジックを実行する安全な方法です。

SQL でのより標準的なアプローチは、相関サブクエリを使用することです。

select t.*,
       (select count(distinct t2.magic_xp)
        from table t2
        where t2.magic_xp >= t.magic_xp
       ) as rank
from table t;
于 2015-08-23T11:47:12.377 に答える
0

クエリ

set @i := 0;
set @lagxp := null;

select id, username, magic_xp, 
@i := if(@lagxp = magic_xp, @i,
          if(@lagxp := magic_xp, @i + 1, @i + 1)) as rank
from hs_users
order by magic_xp desc
;

また

SELECT id, username, magic_xp, 
IF (@score=hs_users.magic_xp, @rank:=@rank, @rank:=@rank+1) as rank,
@score:=hs_users.magic_xp score
FROM hs_users, (SELECT @score:=0, @rank:=0) r
ORDER BY magic_xp DESC;

出力

+-----+------------+----------+------+----------+
| id  |  username  | magic_xp | rank |  lagxp   |
+-----+------------+----------+------+----------+
| 988 | Shapescape | 14926894 |    1 | 14926894 |
| 737 | Ozan       | 13034431 |    2 | 13034431 |
| 989 | Kurt       | 13034431 |    2 | 13034431 |
|   6 | Legacy     |        0 |    3 |        0 |
+-----+------------+----------+------+----------+

sqlfiddle

于 2015-08-23T11:46:22.693 に答える
0
select 
  @rank:=if(magic_xp=@prev_magic_xp,@rank,@rank+1) as rank,
  username,
  magic_xp,
  @prev_magic_xp:=magic_xp as prev_magic_xp

from user,(select @rank:=0,@prev_magic_xp="") t

order by magic_xp desc

参考までに: http://sqlfiddle.com/#!9/09bb3/2

于 2015-08-23T11:59:50.977 に答える
0

解決策を鳴らしてください:)

SELECT id, username, magic_xp, 
IF (@score=hs_users.magic_xp, @rank:=@rank, @rank:=@rank+1) as rank,
@score:=hs_users.magic_xp score
FROM hs_users, (SELECT @score:=0, @rank:=0) r
ORDER BY magic_xp DESC;

@amdixonに感謝

于 2015-08-23T11:48:11.610 に答える