SQL Delete all rows except for last 100

女生的网名这么多〃 提交于 2019-12-25 01:13:15

问题


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.

来源:https://stackoverflow.com/questions/26206009/sql-delete-all-rows-except-for-last-100

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!