2012-05-06 99 views
0

我有以下SQL語句,它似乎正在刪除選定表中的每一行。它應該做的是刪除除難度級別等於1的前10名之外的所有人。刪除除前10行以外的所有行

DELETE FROM Scores 
WHERE Highscore_ID 
NOT IN (SELECT TOP 10 highScore FROM Scores WHERE difficulty = 1 ORDER BY HighScore DESC) 

有關爲什麼這會刪除所有行的任何建議?當運行子查詢時,它會選擇正確的行,但是在刪除時,它似乎要刪除每一行。

回答

3

您將Hichscore_Id與列highScore進行比較。這些列真的具有相同的值嗎?

那麼它應該是

DELETE FROM Scores 
WHERE Highscore_ID NOT IN 
      (SELECT TOP 10 HighScore_ID 
      FROM Scores 
      WHERE difficulty = 1 
      ORDER BY HighScore DESC); 

編輯:

試試這個

DELETE FROM Scores 
JOIN (SELECT ROW_NUMBER() OVER (ORDER BY highscore) AS your_row, * 
     FROM Scores 
     WHERE difficulty = 1 
     ORDER BY HighScore DESC) AS score2 ON score2.HighScore_ID = Scores.HighScore_ID 
WHERE Scores.difficulty = 1 AND score2.your_row>10 
+0

會不會選擇highscore_ID子查詢基礎上的ID號碼,而不是選擇的前10分的id實際的高分? – Euthyphro

+0

那麼你必須爲你的子查詢返回Highscore_Id,但是,那麼訂單就不適合。你必須在你的表格中添加一個普通的等級並刪除所有等級> 11),那麼它就可以工作。 – YvesR

+0

謝謝。 「DELETE FROM SCORE WHERE difficulty = 1 AND Highscore_ID NOT IN(SELECT TOP 10 Highscore_ID FROM Scores WHERE difficulty = 1 ORDER BY highScore DESC);」 – Euthyphro

2

不知道這是一個錯字還是一個真正的錯誤,但您的select子句應該引用highscore_id,而不是高分。

0

我的第一個猜測是「SELECT TOP 10排行榜FROM成績WHERE難度= 1個ORDER BY高分DESC 「可能會返回null。

我的第二個猜測是「highscore_id」不同於「highscore」,所以沒有重疊(並且沒有被刪除)。

肯定仔細檢查你的子查詢,並確保它返回你期望的密鑰!

1

試試這個:

with a as 
(
select ROW_NUMBER() over(order by name) as ordinal, * from test 
) 
delete from a where a.ordinal > 10; 

相關:http://www.ienablemuch.com/2012/03/possible-in-sql-server-deleting-any-row.html


的樣本數據:

CREATE TABLE [beatles] 
    ([name] varchar(14)); 

INSERT INTO [beatles] 
    ([name]) 
VALUES 
    ('john'), 
    ('paul'), 
    ('george'), 
    ('ringo'), 
    ('pete'), 
    ('brian'), 
    ('george martin'); 

查詢:

with a as 
(
    select *, row_number() over(order by name) ordinal 
    from beatles 
) 
delete from a 
where ordinal > 4; 

select * from beatles; 

之前刪除:

NAME 
brian 
george 
george martin 
john 
paul 
pete 
ringo 

刪除後:

NAME 
brian 
george 
george martin 
john 

現場測試:http://www.sqlfiddle.com/#!3/0adcf/6

相關問題