使用MySQL将排名变量添加到数据库
我有一个具有以下结构的数据库:
ID GROUP VALUE RANK
2 1 999 0
1 1 888 0
3 2 777 0
4 2 111 0
我需要通过根据“值”列对ID进行排名和“组”列进行排名来更新“等级”列。基本上,在上面的示例中,我应该结束:
ID GROUP VALUE RANK
2 1 999 1
1 1 888 2
3 2 777 1
4 2 111 2
我尝试按照另一个答案并稍微更改查询:
SET @r=0;
UPDATE `table` SET `RANK` = @r:= (@r+1) ORDER BY `VALUE` DESC;
to to
SET @r=0;
UPDATE `table` SET `RANK` = @r:= (@r+1) PARTITION BY `GROUP` ORDER BY `VALUE` DESC;
to to taf ther thr错误。另外,此方法会产生正确的排名:
SELECT `ID`,
RANK() OVER (PARTITION BY `GROUP` ORDER BY `VALUE`) as `RANK`
FROM table;
但是它不会更新数据库中的“等级”列。我稍微更喜欢第二个解决方案,而不是第一个解决方案,但是如何将查询的输出保存到等级列?
I have a database with the following structure:
ID GROUP VALUE RANK
2 1 999 0
1 1 888 0
3 2 777 0
4 2 111 0
I need to update the "RANK" column by ranking IDs according to the "VALUE" column and grouping by the "GROUP" column. Basically, in the example above, I should end up with:
ID GROUP VALUE RANK
2 1 999 1
1 1 888 2
3 2 777 1
4 2 111 2
I tried following another answer and slightly changing the query:
SET @r=0;
UPDATE `table` SET `RANK` = @r:= (@r+1) ORDER BY `VALUE` DESC;
to
SET @r=0;
UPDATE `table` SET `RANK` = @r:= (@r+1) PARTITION BY `GROUP` ORDER BY `VALUE` DESC;
but this throws an error. Alternatively, this approach produces the correct ranking:
SELECT `ID`,
RANK() OVER (PARTITION BY `GROUP` ORDER BY `VALUE`) as `RANK`
FROM table;
but it does not update the "RANK" column in the database. I slightly prefer the second solution to the first one, but how can I save the output of the query to the RANK column?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在
update> update
语句中,在订单中使用
desc
在订单中使用
desc
在您的最后一个查询中加入表格:Join the table to your last query (also use
DESC
in theORDER BY
clause) in theUPDATE
statement: