简体   繁体   中英

Nested Delete in MySql based on Timestamp

I have a database containing all the content updates for a CMS driven website. 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). The table contains a TIMESTAMP field, and a PAGE ID field to help me find the right rows. The PrimaryKey is a field called 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'

I am running 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?

这是一个疯狂的尝试:

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. You need to create temporary table to get list of most recent rows and then use it in a subquery.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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