我有一个MySQL查询,该查询选择users表中得分最高的3名球员,然后创建一个额外的列,为他们分配排名:
users
SELECT s.*, @curRank := @curRank + 1 AS rank FROM users AS s JOIN ( SELECT DISTINCT highscore FROM users ORDER BY highscore DESC LIMIT 3 ) AS lim ON s.highscore = lim.highscore , (SELECT @curRank := 0) r ORDER BY s.highscore DESC ;
因此,如果表如下所示:
userid name highscore 0 sam 20 1 james 39 2 jack 10 3 harry 46 4 jennie 7
查询的结果将是这样的:
userid name highscore rank 3 harry 46 1 1 james 39 2 0 sam 20 3
如何更改此查询,使其在结果列表中也显示用户及其排名?例如,如果$userName = "jenny"我如何返回:
$userName = "jenny"
userid name highscore rank 3 harry 46 1 1 james 39 2 0 sam 20 3 4 jenny 7 5 <-- Add this row and skip jack
编辑:我应该提到-我正在使用MySQL 5.0.96版
对于8.0之前的版本…
SELECT * FROM ( SELECT a.* , @i := @i+1 i FROM my_table a JOIN (SELECT @i:=0) vars ORDER BY highscore DESC , userid ) x WHERE name = 'jennie' OR i <= 3 ORDER BY i;
https://www.db-fiddle.com/f/hYsiCE1bXeTnR2HzoJkKiR/0