How do I delete rows of data from mysql table automatically with 24 hours after data into table?

后端 未结 2 548
夕颜
夕颜 2020-12-17 04:59

For example, i have a data input program And I want to delete my data automatically after 1 day of this data I input. how I do that?
Someone can explain in code?

相关标签:
2条回答
  • 2020-12-17 05:15

    In your table "portofolio" add column created_at(datetime). Then in Cron Job, check the current datetime exceeds created_at(datetime) with 24hours and delete the records by mysql query like

    DELETE FROM portofolio WHERE created_at<=DATE_SUB(NOW(), INTERVAL 1 DAY)
    

    And run the cron job file every minute

    0 讨论(0)
  • 2020-12-17 05:29

    Try to use regular events. To get started, enable the Event Scheduler using

    SET GLOBAL event_scheduler = ON;
    

    After that you could crate event that will check rows creation time. For example

    CREATE EVENT recycling ON SCHEDULE EVERY 1 HOUR ENABLE 
      DO 
      DELETE FROM MyTable WHERE `timestamp_column` < CURRENT_TIMESTAMP - INTERVAL 24 HOUR;
    

    If there is no column with timestamp of a row creation in your table, then you can create trigger that will insert current timestamp and inserted row identificator to auxiliary table.

    CREATE TRIGGER logCreator AFTER INSERT ON MainTable
      FOR EACH ROW 
      INSERT INTO LogTable (MainID, Created) VALUES(NEW.id, CURRENT_TIMESTAMP);
    

    Then you can use this log to get keys of main table that was created before specific time.

    delimiter |
    CREATE EVENT cleaner ON SCHEDULE EVERY 1 HOUR ENABLE 
      DO 
      BEGIN
        DECLARE MaxTime TIMESTAMP;
        SET MaxTime = CURRENT_TIMESTAMP - INTERVAL 24 HOUR;
        DELETE FROM MainTable 
        WHERE id IN (SELECT MainID FROM LogTable WHERE Created < MaxTime);
        DELETE FROM LogTable WHERE LogTable.Created < MaxTime;
      END |
      delimiter ;
    
    0 讨论(0)
提交回复
热议问题