简体   繁体   中英

MySQL: Select one piece of data per date

In my current project, I am pinging a server hourly every day, which results in 24 records per day; over time, this is a lot of data, and I would like an administrator (in PHP) to be able to pick a date, and delete all of the data before that date, except from one piece of data per day.

Eg if the date selected was 2/4/16, it would delete all but one record per day from before the date 2/4/16.

The structure of the database table in question is:

server_status:
id int(11)
server_id int(11)
time_checked datetime
status char(1)

I was wondering what MySQL statement I would need to achieve this - I've had a look around the web, and I can see that I might need to create new tables, drop the table and replace it, but it seems to be the response that it blocks the db for a long amount of time. It's more the select statement that I'm confused about - I understand how to select the data from before said date, but I don't know how to 1) pick only 1 piece of data per day, and 2) delete the rest.

Thank you so much for your help!

You should be able to achieve that using the following query.

SET @date_param = '2016-04-02';

DELETE FROM server_status WHERE time_checked < @date_param AND id NOT IN (
    SELECT id FROM (
        SELECT MIN(id) AS id
        FROM server_status
        WHERE time_checked < @date_param
        GROUP BY DATE(time_checked) 
    ) AS ids_to_keep
)

Obviously you can replace the sql variable/parameter with a php/bound one if you wish.

The reason the sub query is wrapped in an extra select, is because in MySQL, you can't modify the same table that you use in the SELECT part. Wrapping the extra select creates an implicit temporary table, but seems to be the easiest and cleanest approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM