我有一张包含我的游戏得分的表格
CREATE TABLE Scores
(
PlayerName varchar(50),
LevelId integer,
Score integer,
Difficulty integer
);
并且我想始终将分数条目的数量限制为 10 个元素(针对特定级别和难度)
因此,当分数表有 10 个条目(针对特定级别和难度)并且玩家有新的高分时,我想删除最后一个元素(最低分数),并插入新的高分。我怎样才能做到这一点?
我有一张包含我的游戏得分的表格
CREATE TABLE Scores
(
PlayerName varchar(50),
LevelId integer,
Score integer,
Difficulty integer
);
并且我想始终将分数条目的数量限制为 10 个元素(针对特定级别和难度)
因此,当分数表有 10 个条目(针对特定级别和难度)并且玩家有新的高分时,我想删除最后一个元素(最低分数),并插入新的高分。我怎样才能做到这一点?
怎么样...
DELETE FROM Scores S1
WHERE Score < (SELECT MIN(Score)
FROM (SELECT Score
FROM Scores S2
WHERE S1.Level = S2.Level AND
S1.Difficulty = S2.Difficulty
ORDER BY Score DESC
LIMIT 10) AS Derived);
尽管这不适用于每个数据库。If 也不会将表格限制为十行,如果超过一个分数在第十位是水平的。
稍后 - 编辑以纠正 Andomar 指出的错误。
DELETE FROM Scores
WHERE LevelID = ? AND Difficulty = ?
ORDER BY Score ASC
LIMIT 1
应该删除最低分。但即使这是你想要的,也可能不是你需要的。:)
delete from Scores
where playerName+'|'+cast(levelID as varchar)+'|'+cast(Difficulty as varchar)+'|'+cast(score as varchar)
in(
select playerName+'|'+cast(levelID as varchar)+'|'+cast(Difficulty as varchar)+'|'+cast(score as varchar) from
(Select rank() over (partition by cast(levelID as varchar)+'|'+cast(Difficulty as varchar) order by score desc) as bRank,*
from Scores as b) as Ranks
where Ranks.bRank >= 10)
你可以用你的主键替换 playerName+'|'+cast(levelID as varchar)+'|'+cast(Difficulty as varchar)+'|'+cast(score as varchar)
这将为您提供第 10 位及以后的球员:
select Ranks.* from
(Select rank() over (partition by cast(levelID as varchar)+'|'+cast(Difficulty as varchar)
order by score desc) as bRank,*
from Scores as b) as Ranks
where Ranks.bRank >= 10
结果:
bRank playerName LevelID Score Difficulty
-------------------- -------------------------------------------------- ----------- ----------- -----------
10 Player 3 1 3 10
11 Player 2 1 2 10
12 Player 1 1 1 10