我正试图绕过一个查询而我无法理解。如果有人给我指针,我将不胜感激。作为我想要实现的一个简单示例,我在数据库中有这些记录
Score|Ranking
-------------
100 |0
200 |0
300 |0
我希望排名字段包含1,2,3根据谁获得最高分,所以结果应为:
Score|Ranking
-------------
100 |3
200 |2
300 |1
目前,我正在为所有这些记录做下一个循环,但实际上可能是几千个 - 这可能需要永远!有没有人对魔法查询有所了解,可以一次性做到这一点?
答案 0 :(得分:18)
这是一种方法:
SET @r=0;
UPDATE table SET Ranking= @r:= (@r+1) ORDER BY Score DESC;
/* use this if you just want to pull it from the db, but don't update anything */
SET @r=0;
SELECT *, @r:= (@r+1) as Ranking FROM table ORDER BY Score DESC;
答案 1 :(得分:5)
在MySQL中,您可以使用row_number 。
Here's an example在SELECT
中使用它:
select @rownum:=@rownum+1 ‘rank’, p.*
from player p, (SELECT @rownum:=0) r
order by score desc;
如果您INSERT INTO
使用SELECT
这样的话,您将获得排名。
答案 2 :(得分:5)
这会创建一个内联更新语句,按照变量@rc
对您的玩家进行排名。我在非常类似的情况下多次使用它,它运行良好并且保留在数据库端。
SET @rc = 0;
UPDATE players JOIN (SELECT @rc := @rc + 1 AS rank, id FROM players ORDER BY rank DESC)
AS order USING(id) SET players.rank = order.rank;
id
被假定为players
表的主键。
答案 3 :(得分:2)
SET @r = 0;
UPDATE players JOIN (SELECT @r := @r + 1 AS rank, id FROM players ORDER BY rank DESC)
AS sorted USING(id) SET players.rank = sorted.rank;
答案 4 :(得分:0)
我告诉你我的方式[用于间隔sql更新功能]
选择
set @currentRank = 0,
@lastRating = null,
@rowNumber = 1;
select
*,
@currentRank := if(@lastRating = `score`, @currentRank, @rowNumber) `rank`,
@rowNumber := @rowNumber + if(@lastRating = `score`, 0, 1) `rowNumber`,
@lastRating := `score`
from `table`
order by `score` desc
更新
set @currentRank = 0,
@lastRating = null,
@rowNumber = 1;
update
`table` r
inner join (
select
`primaryID`,
@currentRank := if(@lastRating = `score`, @currentRank, @rowNumber) `rank`,
@rowNumber := @rowNumber + if(@lastRating = `score`, 0, 1) `rowNumber`,
@lastRating := `score`
from `table`
order by `score` desc
) var on
var.`primaryID` = r.`primaryID`
set
r.`rank` = var.`rank`
我没有对此测试进行任何性能检查,除非测试它是否有效
答案 5 :(得分:0)
如果您使用的是MySQL 8,那么可以使用新功能RANK()
this.$refs.glitchOne.addEventListener("animationend", function () {
根据您希望以均匀分数显示排名的方式,这样您还可以签出DENSE_RANK()
作为更新:
String find(List<ProjectCode> projectCodeList, String projectTitle) {
return projectCodeList
.firstWhere(
(projectCode) => projectCode.projectTitle.contains(projectTitle))
.id;
}