删除除前10行之外的所有行

时间:2012-05-06 07:51:45

标签: sql sql-server sql-delete

我有以下SQL语句,它似乎正在删除所选表中的每一行。它应该做的是删除除了难度级别等于1的前10名之外的所有内容。

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

有关为什么会删除所有行的任何建议?在运行子查询时,它会选择正确的行,但是,在删除时,它似乎想要删除每一行。

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

不知道这是拼写错误还是真正的错误,但你的select子句应该引用highscore_id,而不是高分。

答案 2 :(得分: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

答案 3 :(得分:0)

我的第一个猜测是" SELECT TOP 10 highScore FROM得分WHERE难度= 1 ORDER BY HighScore DESC"可能会返回null。

我的第二个猜测是" highscore_id"与" highscore"不同,所以没有重叠(没有删除任何内容)。

绝对仔细检查您的子查询,并确保它返回您期望的密钥!