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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 12:15:22  来源:igfitidea点击:

Delete Top-N' Rows from a Table with some sorting(order by 'Column')

sqlsql-servertsql

提问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 3clause to the subselect:

top 3子句添加到子选择中:

Delete from Table1 
where id IN (
    select top 3 id 
    from Table1 
    order by id desc
)