简体   繁体   English

基于时间戳在MySql中嵌套删除

[英]Nested Delete in MySql based on Timestamp

I have a database containing all the content updates for a CMS driven website. 我有一个数据库,其中包含CMS驱动的网站的所有内容更新。 I want to create a query that will clean out all the old stuff, but leave me the most recent few (5) copies of each page (just in case). 我想创建一个查询,该查询将清除所有旧内容,但请留给我每页最近的几(5)份副本(以防万一)。 The table contains a TIMESTAMP field, and a PAGE ID field to help me find the right rows. 该表包含一个TIMESTAMP字段和一个PAGE ID字段,以帮助我找到正确的行。 The PrimaryKey is a field called RevisionId. PrimaryKey是一个名为RevisionId的字段。 There are of course other fields (containing the page content for example), but they are irrelevant to this question. 当然还有其他字段(例如包含页面内容),但它们与该问题无关。

I have this query working fine: 我有这个查询工作正常:

  SELECT RevisionId 
    FROM `content` 
   WHERE PageId='55' 
ORDER BY Timestamp DESC LIMIT 5;

It returns five entries that I wish to save. 它返回五个要保存的条目。

I thought I could nest it like this: 我以为可以这样嵌套:

DELETE 
  FROM `content` 
 WHERE PageId='55' 
   AND RevisionId NOT IN ( 
           SELECT RevisionId 
             FROM `content` 
            WHERE PageId='55' 
         ORDER BY Timestamp DESC LIMIT 5 );

...but that gives me an error: ...但这给了我一个错误:

#1235 - This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery' #1235-此版本的MySQL尚不支持“ LIMIT&IN / ALL / ANY / SOME子查询”

I am running MySQL 5. 我正在运行MySQL 5。

Two part question: 两部分问题:

  1. What do I need to do to resolve the error I am getting thus far? 我需要做些什么来解决我到目前为止遇到的错误?
  2. Is there a way to further automate this to run through my entire table...not just PageId='55' but all distinct PageId numbers? 有没有办法使它进一步自动化以遍及我的整个表...不仅仅是PageId = '55',而是所有不同的PageId号码?

这是一个疯狂的尝试:

DELETE c FROM `content` AS c WHERE PageId='55' AND NOT EXISTS ( SELECT 1 FROM `content` WHERE PageId='55' AND c.RevisionId = content.RevisionId ORDER BY content.Timestamp DESC LIMIT 5 );

Currently mysql can't process delete statements with subqueries to the same table. 目前,mysql无法处理带有同一表子查询的delete语句。 You need to create temporary table to get list of most recent rows and then use it in a subquery. 您需要创建临时表以获取最新行的列表,然后在子查询中使用它。

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

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