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.
Deleting large portions of a table isn't always the only answer. If you are deleting 95% of a table and keeping 5%, it can actually be quicker to move the rows you want to keep into a new table, drop the old table, and rename the new one. Or copy the keeper rows out, truncate the table, and then copy them back in.
Users can delete records from the database either individually or in batches.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With