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`
WHE开发者_开发百科RE 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:
- What do I need to do to resolve the error I am getting thus far?
- Is there a way to further automate this to run through my entire table...not just PageId='55' but all distinct PageId numbers?
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.
This is a wild try:
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 );
精彩评论