order_id | order_sn | total_price | enterdate |
---|---|---|---|
25396 | A4E610E250C2D378D7EC94179E14617F | 2306.00 | 2017-04-01 17:23:26 |
25397 | EAD217C0533455EECDDE39659ABCDAE9 | 17.90 | 2017-04-01 22:15:18 |
25398 | 032E6941DAD44F29651B53C41F6B48A0 | 163.03 | 2017-04-02 07:24:36 |
此時查詢某月各天下單數,總金額應當如何做呢?
一般方法
首先最容易想到的方法,先利用 php 函數 cal_days_in_month()
獲取當月天數,然后構造一個當月所有天的數組,然后在循環中查詢每天的總數,構造新數組。
代碼如下:
$month = '04'; $year = '2017'; $max_day = cal_days_in_month(CAL_GREGORIAN, $month, $year); //當月最后一天 //構造每天的數組 $days_arr = array(); for($i=1;$i=$max_day;$i++){ array_push($days_arr, $i); } $return = array(); //查詢 foreach ($days_arr as $val){ $min = $year.'-'.$month.'-'.$val.' 00:00:00'; $max = $year.'-'.$month.'-'.$val.' 23:59:59'; $sql = "select count(*) as total_num,sum(`total_price`) as amount from `orders` where `enterdate` >= {$min} and `enterdate` = {$max}"; $return[] = mysqli_query($sql); } return $return;
這個sql簡單,但是每次需要進行30次查詢請,嚴重拖慢響應時間。
優化
如何使用一個sql直接查詢出各天的數量總計呢?
此時需要利用 mysql 的 date_format
函數,在子查詢中先查出當月所有訂單,并將 enterdate 用 date_format 函數轉換為 天 ,然后按天 group by
分組統計。 代碼如下:
$month = '04'; $year = '2017'; $max_day = cal_days_in_month(CAL_GREGORIAN, $month, $year); //當月最后一天 $min = $year.'-'.$month.'-01 00:00:00'; $max = $year.'-'.$month.'-'.$max_day.' 23:59:59'; $sql = "select t.enterdate,count(*) as total_num,sum(t.total_price) as amount (select date_format(enterdate,'%e') as enterdate,total_price from orders where enterdate between {$min} and {$max}) t group by t.enterdate order by t.enterdate"; $return = mysqli_query($sql);
如此,將30次查詢減少到1次,響應時間會大大提高。
注意:
1.由于需查詢當月所有數據,在數據量過大時,不宜采取本方法。
2.為避免當天沒有數據而造成的數據缺失,在查詢后,理應根據需求對數據進行處理。
更多關于PHP相關內容感興趣的讀者可查看本站專題:《php+mysql數據庫操作入門教程》、《php+mysqli數據庫程序設計技巧總結》、《php面向對象程序設計入門教程》、《PHP數組(Array)操作技巧大全》、《php字符串(string)用法總結》及《php常見數據庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。
下一篇:簡單談談PHP的垃圾回收機制