从表中删除具有一些排序的前N行(按'列'排序)

时间:2012-11-22 08:09:21

标签: sql sql-server tsql

我对某些专栏删除前N行的订单感到困惑。

我在这里创建了一个例子Example at fiddle

这些查询有什么问题?

 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)

因为在mysql中,limit关键字能够很好地完成工作

2 个答案:

答案 0 :(得分:66)

您可以使用CTE执行faster ordered delete,而无需单独的子查询来检索前3个ID。

WITH T
     AS (SELECT TOP 3 *
         FROM   Table1
         ORDER  BY id DESC)
DELETE FROM T 

答案 1 :(得分:10)

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

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