SQL Delete all rows except for last 100

2019-09-01 07:14发布

问题:

I have a database that adds a large number of rows to it each day. It got to the point where in around a week there were over 30k records. I really only need the latest 100 records, so I want to routinely go in and delete any record that is not the latest 100 records for each page.. However I do have one or two exceptions that need to be handled as well.

I have tried doing this:

$wpdb->query($wpdb->prepare("
                            DELETE FROM wp_tintup 
                            WHERE sponsored=''
                            AND pageID = '$pageID'
                            AND NOT EXISTS (
                                            SELECT * FROM wp_upvotes 
                                            WHERE wp_tintup.tintupID = wp_upvotes.postID
                                            )
                            ORDER BY id DESC
                            LIMIT 100, 1000000
                             "));

Obviously, LIMIT doesn't work in a DELETE like this, so I need a way of doing this...

There is one thing that I do need to add to this. I want to keep the last 100 rows disregarding the result of the sub query.

There may be say 3 results for the sub query, so in that case for that pageID it should have 103 records when it is finished.