SQL 使用某种排序从表中删除前 N 行(按“列”排序)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13508280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Delete Top-N' Rows from a Table with some sorting(order by 'Column')
提问by Shah
I am having some confusion regarding Deleting the top N Rows order by some column.
我对按某些列删除前 N 行顺序有些困惑。
I created have an example here Example at fiddle
我在这里创建了一个示例小提琴示例
What is wrong with these queries?
这些查询有什么问题?
Delete Top(3) from Table1 order by id desc
Delete Top(3) from Table1
where id IN (select id from Table1 order by id desc)
Since in mysql the limit keyword does the job very well
由于在 mysql 中 limit 关键字可以很好地完成这项工作
回答by Martin Smith
You can use a CTE to do a faster ordered deletewithout the need for a separate sub query to retrieve the top 3 ids.
您可以使用 CTE 进行更快的有序删除,而无需单独的子查询来检索前 3 个 ID。
WITH T
AS (SELECT TOP 3 *
FROM Table1
ORDER BY id DESC)
DELETE FROM T
回答by Cristian Lupascu
Add the top 3
clause to the subselect:
将top 3
子句添加到子选择中:
Delete from Table1
where id IN (
select top 3 id
from Table1
order by id desc
)