duanbo6482 2016-05-03 10:45
浏览 9
已采纳

MySQL:每个日期选择一个数据

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.

E.g. 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!

  • 写回答

1条回答 默认 最新

  • douyong5825 2016-05-04 03:53
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)