2010-07-08 85 views
0

的最後一排我有一個包含我的遊戲如何刪除查詢

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

,我想永遠限制評分項10種元素的數量(特定水平的成績表,和難度)

所以當分數表有10個條目(對於特定的水平和難度)並且玩家有新的高分時,我想刪除最後一個元素(最低分數),並插入新的高分。我怎樣才能做到這一點?

+0

您正在使用的數據庫? MySQL的? – Andomar 2010-07-08 08:51:34

+1

爲什麼不只是存儲所有的分數,並選擇前10名? 否則,觸發器應該做的工作 – BenW 2010-07-08 08:51:57

+0

我使用SQLite – penpen 2010-07-08 09:04:03

回答

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指出的錯誤。

+2

子查詢只選擇聚合,所以它會返回確切的一行。'limit 10'沒有效果。 – Andomar 2010-07-08 09:02:54

+0

D'oh!你說得很對,我會編輯它並更正。 – 2010-07-08 09:06:44

+0

謝謝你,它的工作原理!:D – penpen 2010-07-08 09:45:21

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

應刪除最低分。但即使這是你想要的,它可能不是你所需要的。 :)

+0

它看起來不錯,但你爲什麼說它可能不是我需要? 我檢查它,並告訴你它是否工作 – penpen 2010-07-08 09:07:32

+0

這是一個與SQLite的語法錯誤:( 「SQL錯誤:接近」訂單「:語法錯誤」 – penpen 2010-07-08 09:32:11

+0

可能是我用MySQL寫的,但一切都好@Cooper:+1。 – Amadan 2010-07-08 17:54:17

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爲varchar)+ '|' |你的主鍵

+投(得分爲varchar)+投(難度爲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