Skip to content
Advertisement

Get SQL data individually for days between now and 30 days ago

I’m building an analytics chart where I need to display the number of visits for each day, for the past 30 days. I’ve tried using the loop below, but it fails to pull certain data and drastically slows down page load time, due to 30 queries being sent in one request.

Are there any better ways to get this data from the MySQL database while saving server resources and improving the load time of the page? Any help is appreciated.

JavaScript

Advertisement

Answer

If you have at least one visit per day, you can just use aggregation:

JavaScript

Having a column called date is somehow misleading (although MySQL allows it). For the sake of clarity, I renamed the column to dt in the query.

If there are days without visits, and you still want to display them, with a count of 0 visits, then it is a bit more tricky. You need to generate the dates first, then left join the table. You would typically use a calendar table – or, in MySQL 8.0, you can do this on the fly with a recursive common table expression:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement