简体   繁体   中英

SELECT MAX BETWEEN 00:01 and 23:59 on set day - SQL

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.

I think you wanto to drop time part, so you can use date function which drops time.

$query = $this->db->query("SELECT MAX(total_online)AS total FROM network_traffic
WHERE network_id = '$network_id' AND timestamp >= date(NOW() - INTERVAL $days DAY) 
AND timestamp <= date(NOW() - INTERVAL $offset DAY)");
function set_day_peak($days, $offset, $network_id){

    $days = $days + $offset;
    $next = $days - 1;
    $query = $this->db->query("
       SELECT MAX(total_online) AS total
         FROM network_traffic
        WHERE network_id = '$network_id'
          AND timestamp >= DATE(NOW() - INTERVAL $days DAY) 
          AND timestamp <  DATE(NOW() - INTERVAL $next DAY)");
    $data = $query->row();

    return $data->total;
}

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:

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 DATE(timestamp) = DATE(NOW() - INTERVAL $days DAY)");
    $data = $query->row();

    return $data->total;
}

This may not be as efficient as it is much harder for the optimizer to use an index on timestamp because of the function call on timestamp . You should experiment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM