【问题标题】:Update mysql rank by column value grouped by column value按列值分组的列值更新mysql排名
【发布时间】:2016-04-16 00:24:13
【问题描述】:

从这些例子开始。

1 mysql rank by column value grouped by column value

2Multiple Ranks in one table

他们解释了如何计算按列值分组的排名。在我的情况下 ship

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

| 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;

【问题讨论】:

  • 所以您正在寻找更新声明? tutorialspoint.com/mysql/mysql-update-query.htm
  • 是的。我需要更新:)
  • 为什么要有人为您编写代码。至少自己试一试。如果您遇到问题,请回来并提出具体问题。
  • 请提供您尝试编写的代码示例。
  • 我认为从标题中可以清楚地看到这一点。我做了选择。但我无法进行更新。该示例在我制作的架构中。并在选择查询中。

标签: mysql rank


【解决方案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

【讨论】:

    猜你喜欢
    • 2014-07-24
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多