我想保留VMR
表中的最后20条记录并删除所有其他记录。 VMR表有5000000
条记录及其增长。我还有create_date列,date datatype
表中有VMR
,它有非唯一索引。我尝试使用rownum删除记录并使用下面的查询保留最后20条记录,但是它花了太多时间删除。有没有其他方法可以更快地运行查询。
delete from VMR
where rowid not in
(select rowid
from VMR
where rownum <=20);
答案 0 :(得分:3)
只是为了表明另一种选择:
-- 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;
答案 1 :(得分:1)
尝试使用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