简体   繁体   English

保留最后20条记录并删除oracle sql中的其他记录

[英]Keep the last 20 records and delete other records in oracle sql

I want to keep the last 20 records in VMR table and delete all other records. 我想在VMR表中保留最后20条记录,并删除所有其他记录。 The VMR table has 5000000 records and its growing. VMR表具有5000000条记录,并且正在增长。 I also have create_date column which has date datatype in VMR table and it has non unique index. 我也有create_date列,该列在VMR表中具有date datatype ,并且具有非唯一索引。 I tried using rownum to delete the records and keep the last 20 records using below query but its taking too much time for deletion. 我尝试使用rownum删除记录,并使用下面的查询保留最后20条记录,但是删除它花费了太多时间。 Is there any other way to run the query faster. 还有其他方法可以更快地运行查询。

delete from VMR
 where rowid not in 
       (select rowid
          from VMR
         where rownum <=20);

Just to show an alternative: 只是为了显示一个替代方案:

-- get 20 last records and remember them
create table vmr20 as
  select * from vmr order by create_date desc fetch first 20 rows only;

-- empty table via DDL which should be fastest
truncate vmr;

-- re-insert the last 20 rows
insert into vmr
  select * from vmr20;

-- delete temp table
drop table vmr20;

Try using ROW_NUMBER() 尝试使用ROW_NUMBER()

WITH CTE AS (
SELECT t.*,
       ROW_NUMBER() OVER(ORDER BY create_date DESC) as rnk
FROM VMR t)
DELETE FROM CTE 
WHERE CTE.rnk > 20

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM