views:

3970

answers:

3

Assume a table with the following columns:

pri_id, item_id, comment, date

What I want to have is a SQL query that will delete any records, for a specific item_id that are older than a given date, BUT only as long as there are more than 15 rows for that item_id.

This will be used to purge out comment records older than 1 year for the items but I still want to keep at least 15 records at any given time. This way if I had one comment for 10 years it would never get deleted but if I had 100 comments over the last 5 days I'd only keep the newest 15 records. These are of course arbitrary record counts and date timeframes for this example.

I'd like to find a very generic way of doing this that would work in mysql, oracle, postgres etc. I'm using phps adodb library for DB abstraction so I'd like it to work well with that if possible.

+5  A: 

Something like this should work for you:

delete
from
  MyTable
where
  item_id in
  (
    select
      item_id
    from
      MyTable
    group by
      item_id
    having
      count(item_id) > 15
  )
  and
    Date < @tDate
Robert C. Barth
A: 

Is this what you're looking for?

DELETE
    [MyTable]
WHERE
    [item_id] = 100 and
    (SELECT COUNT(*) FROM [MyTable] WHERE [item_id] = 100) > 15

I'm a MS SQL Server guy, but i think it should work elsewhere.

Jeremy
Where is the Date catch? Try again! :)
Craig
+2  A: 

You want to keep at least 15 of them always, correct? So:

    DELETE
    FROM    CommentTable
    WHERE   CommentId NOT IN (
         SELECT TOP 15 CommentId
         FROM CommentTable
         WHERE ItemId=@ItemId
         AND CommentDate < @Date
            ORDER BY CommentDate DESC
    )
    AND ItemId=@ItemId
    AND CommentDate < @Date
Rorschach