I want to get the data every day within one year backward but I have to use 365 queries for each day like:
for ($i = 0; $i<365; $i++){
$end_day = ...; // the end time of each day
$start_day = ...; // the start time of each day
$query = select count(*)....where created < $end_day AND created > $start_day
}
I think that my current solution makes the system very slow. Is there any way to just use one query only?
Assuming that your created column is a DATETIME or TIMESTAMP, and the data stored is more granular than a day:
SELECT COUNT(*) … GROUP BY YEAR(created), MONTH(created), DAY(created)
COUNT is an aggregate function and will apply to each group, i.e. you will have one row per group and that row will have the number of records in that group. As we’ve made a group a day, this is the data you want.
You cannot just group by DAY(created) as DAY returns the day of the month, so we also need to put month and year in to make sure days are discrete.
You probably want to have a WHERE created > $start AND created < $finish to limit it to some time frame (or a WHERE YEAR(created) == 2010).
References:
MySQL Query GROUP BY day / month / year
http://dev.mysql.com/doc/refman/5.1/en/group-by-functions.html