简体   繁体   English

SQL删除表中最旧的记录

[英]SQL to delete the oldest records in a table

I'm looking for a single SQL query to run on an oracle table that will retain n number of records in a table and delete the rest 我正在寻找一个在oracle表上运行的SQL查询,它将在表中保留n个记录并删除其余的

I tried the following 我尝试了以下内容

delete from myTable where pk not in 
(SELECT pk FROM myTable where rownum <5 order by created DESC)

But it appears that I cannot have order by in the nested select. 但似乎我无法在嵌套选择中进行order by

Any help appreciated 任何帮助赞赏

When you use ORDER BY with ROWNUM the ROWNUM is applied first, so you don't get the results you expect. 当您使用ORDER BY和ROWNUM时,首先应用ROWNUM,因此您无法获得预期的结果。 You could modify your SQL to: 您可以将SQL修改为:

delete from myTable where pk not in 
( SELECT pk FROM 
   ( SELECT pk FROM myTable  order by created DESC)
  where rownum <5
)

There are many other ways to write this. 还有很多其他方法可以写这个。 If the table is large and most rows will be deleted then maybe this will be faster: 如果表很大并且大多数行将被删除,那么这可能会更快:

delete from myTable where created < 
( SELECT MIN(created) FROM 
   ( SELECT created FROM myTable order by created DESC)
  where rownum <5
)

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

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