按列值分组的列值更新mysql排名

时间:2016-04-16 00:24:13

标签: mysql rank

从这些例子开始。

1 mysql rank by column value grouped by column value

2 Multiple Ranks in one table

他们解释了如何计算按列值分组的等级。就我而言发货

我需要更新的“排名”列, 而不是选择

| iduser | ship  | score | rank  |
+--------+-------+-------+-------+
|   25   |   1   |   7   |   0   |
|   25   |   3   |  21   |   0   |
|   25   |   4   |  30   |   0   |
|   12   |   9   |  23   |   0   |
|   25   |   9   |  18   |   0   |
|   21   |   9   |   5   |   0   |

必须更新:

| iduser | ship  | score | rank  |
+--------+-------+-------+-------+
|   25   |   1   |   7   |   1   |
|   25   |   3   |  21   |   1   |
|   25   |   4   |  30   |   1   |
|   12   |   9   |  23   |   1   |
|   25   |   9   |  18   |   2   |
|   21   |   9   |   5   |   3   |

这是选择查询

SELECT  iduser,
        ship,
        score,
        ( 
            CASE ship 
            WHEN @curShip 
            THEN @curRow := @curRow + 1 
            ELSE @curRow := 1 AND @curShip := ship END
        ) AS rank
FROM    ship_stats,
        (SELECT @curRow := 0, @curShip := '') r
ORDER BY ship DESC, score DESC;

1 个答案:

答案 0 :(得分:1)

SET @curship = 0,@curRow = 0;
UPDATE ship_stats 
SET rank := 
        (CASE ship 
            WHEN @curShip 
            THEN @curRow := @curRow + 1 
            ELSE @curRow := 1 AND @curShip := ship END
        )
ORDER BY ship DESC, score DESC;

sqlfiddle