如何删除查询的最后一行

时间:2010-07-08 08:49:27

标签: sql sqlite delete-row sql-delete

我有一张包含游戏分数的表格

CREATE TABLE Scores
(
  PlayerName varchar(50),
  LevelId integer,
  Score integer,
  Difficulty integer
);

我希望始终将分数条目的数量限制为10个元素(针对特定级别和难度)

因此,当得分表有10个条目(针对特定级别和难度)并且玩家有新的高分时,我想删除最后一个元素(最低分数),并插入新的高分。我怎么能这样做?

3 个答案:

答案 0 :(得分:2)

怎么样......

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

虽然这不适用于每个数据库。如果在第十个位置有多个得分水平,也不会将表限制为十行。

稍后 - 编辑以纠正Andomar指出的错误。

答案 1 :(得分:0)

DELETE FROM Scores
WHERE LevelID = ? AND Difficulty = ?
ORDER BY Score ASC
LIMIT 1

应删除最低分。但即使这是你想要的,也可能不是你需要的。 :)

答案 2 :(得分:0)

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(难度为varchar)+'|'+ cast(得分为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