0
DELIMITER |

CREATE EVENT myevent
    ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 MINUTE
    DO
      BEGIN
        DELETE FROM vehicle WHERE last_updated < (NOW() - INTERVAL 5 MINUTE)
      END |

DELIMITER ;

Above I have a MySQL event that runs every minute deleting rows that haven't been updated for 5 minutes. I have another table called saved_vehicles. All of the rows in vehicle will have a row in the saved_vehicle table. What I want to do is essentially copy over the last_updated time to the saved_vehicle table (for example purposes, imagine the saved_vehicle field would be last_known_online_time. This essentially saves a copy of the vehicle with its last known online time.

Essentially I'm creating a backup before deleting the row.

jskidd3
  • 4,609
  • 15
  • 63
  • 127

1 Answers1

0

Insert into saved_vehicles before delete. Try this:

DELIMITER |

CREATE EVENT myevent
    ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 MINUTE
    DO
      BEGIN
        SET @time = NOW() - INTERVAL 5 MINUTE;

            # select * is not very smart, it will also copy your primary key, 
            # so you can get error about duplicates. Listing fields would work here.
        INSERT INTO saved_vehicle (SELECT * FROM vehicle WHERE last_updated < @time); 
        DELETE FROM vehicle WHERE last_updated < @time;

      END |

DELIMITER ;

To avoid listing fields i've mentioned in comment try to select all fields except your primary key column. To do this check how to select all columns except one

update
I through about insert i mentioned above - and if your saved_vehicle table has same structure as vehicle table, but its primary key has different name than vehicle (f.e. base_id, when vehicle PK is id) and its int auto_increment then it will work nice as it is.

Community
  • 1
  • 1
michalczukm
  • 9,963
  • 6
  • 40
  • 47