I have the following function in my codeigniter app
function set_day_peak($days, $offset, $network_id){
$days = $days + $offset;
$query = $this->db->query("SELECT MAX(total_online)AS total FROM network_traffic
WHERE network_id = '$network_id' AND timestamp >= NOW() - INTERVAL $days DAY
AND timestamp <= NOW() - INTERVAL $offset DAY");
$data = $query->row();
return $data->total;
}
The above function does return a value but its not accurate, what i need when i call
$this->set_day_peak(1,7,14)
is for it to return the max(total_online) from 00:01 to 23:59 on day 1 with a 7 day offset or (8 days ago).
As i am not brilliant with sql yet the only solution i could manage would be to use php to set the timestamps ie ($day_start and $day_end) then use SELECT MAX BETWEEN but i would like to see if it can be done with pure SQL Any ideas would be much appreciated.
This formatting (whether legal or not) makes the SQL structure clear. The DATE function truncates the time value part of its argument expression. The comparison with a timestamp ‘adds zeros back’ for the time components. This should select the maximum of all values recorded for a given 24 hour period. The asymmetric conditions (‘>=’ vs ‘<‘) are important.
An alternative formulation would be:
This may not be as efficient as it is much harder for the optimizer to use an index on
timestampbecause of the function call ontimestamp. You should experiment.