Search code examples
mysqlsqlmysql-event

Schedule MySQL query every 24 hours; query table and store results in another table


I need this query:

SELECT ItemID, Price 
        FROM table
        WHERE ItemID = %d
        GROUP BY Price
        ORDER BY COUNT(*) DESC LIMIT 1

-run once a day, and have the results from it stored in another table with the time stamp of the query.

Is there a way I can automatically query all the available ItemID values? For example, if there are 20 ItemID values available, I need 20 separate queries.


Solution

  • You can use the mysql event scheduler for this. Here's an example with your current query inserting data into a table called "new_table", starting at 3 AM on March 28.

    DELIMITER $$
    
    CREATE 
        EVENT `daily_backup` 
        ON SCHEDULE EVERY 1 DAY STARTS '2015-03-28 03:00:00' 
        DO BEGIN
    
            INSERT INTO new_table (ItemID, Price, Time) 
                SELECT ItemID, Price, NOW()
                FROM table
                WHERE ItemID = %d
                GROUP BY Price
                ORDER BY COUNT(*) DESC LIMIT 1;
    
    
        END */$$
    

    You can do the same thing with your other queries; they can be put into the same event, before the END