Mysql – Caching A Query Daily

cacheMySQL

How to ensure a query runs only once a day in MySQL? Once it runs, returned result should be cached, and even though returned data were changed in database, my query's results should remain the same during the same day. Is that possible?

Point of my this question:

I want to put some statistics on the dashboard of my admin panel. But calculating the statistics keep long time. So, If these calculations is done only one time, it really saves lots of time of my clients and my server.

Best Answer

Yes, it is possible. Use MySQL's EVENT mechanism. As the documentation says, it's the MySQL equivalent of cron or the Windows Task Scheduler. An overview is available from here and an example here. They can also be seen as TRIGGERs fired by a time rather than by SQL.

Be sure to enable events via the global system variable event_scheduler as explained here.

You can set up an event to run at 00:01 and store the result in a table and then your app can refer to that table throughout the day, safe in the knowledge that the value won't change until 1 minute past midnight the following day (or whenever suits you).