我有以下 SQL 语句,它似乎正在删除所选表中的每一行。它应该做的是删除除难度级别等于 1 的前 10 名之外的所有内容。
DELETE FROM Scores
WHERE Highscore_ID
NOT IN (SELECT TOP 10 highScore FROM Scores WHERE difficulty = 1 ORDER BY HighScore DESC)
关于为什么这会删除所有行的任何建议?运行子查询时,它会选择正确的行,但是,在删除时,它似乎想要删除每一行。
我有以下 SQL 语句,它似乎正在删除所选表中的每一行。它应该做的是删除除难度级别等于 1 的前 10 名之外的所有内容。
DELETE FROM Scores
WHERE Highscore_ID
NOT IN (SELECT TOP 10 highScore FROM Scores WHERE difficulty = 1 ORDER BY HighScore DESC)
关于为什么这会删除所有行的任何建议?运行子查询时,它会选择正确的行,但是,在删除时,它似乎想要删除每一行。
您将 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
不知道这是拼写错误还是真正的错误,但您的 select 子句应该引用 highscore_id,而不是 highscore。
尝试这个:
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
我的第一个猜测是“SELECT TOP 10 highScore FROM Scores WHERE难度= 1 ORDER BY HighScore DESC”可能返回空值。
我的第二个猜测是“highscore_id”与“highscore”不同,因此没有重叠(也没有任何内容被删除)。
绝对要仔细检查您的子查询,并确保它返回您期望的键!