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 |
此時查詢某月各天下單數(shù),總金額應(yīng)當(dāng)如何做呢?
一般方法
首先最容易想到的方法,先利用 php 函數(shù) cal_days_in_month()
獲取當(dāng)月天數(shù),然后構(gòu)造一個當(dāng)月所有天的數(shù)組,然后在循環(huán)中查詢每天的總數(shù),構(gòu)造新數(shù)組。
代碼如下:
$month = '04'; $year = '2017'; $max_day = cal_days_in_month(CAL_GREGORIAN, $month, $year); //當(dāng)月最后一天 //構(gòu)造每天的數(shù)組 $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次查詢請,嚴(yán)重拖慢響應(yīng)時間。
優(yōu)化
如何使用一個sql直接查詢出各天的數(shù)量總計呢?
此時需要利用 mysql 的 date_format
函數(shù),在子查詢中先查出當(dāng)月所有訂單,并將 enterdate 用 date_format 函數(shù)轉(zhuǎn)換為 天 ,然后按天 group by
分組統(tǒng)計。 代碼如下:
$month = '04'; $year = '2017'; $max_day = cal_days_in_month(CAL_GREGORIAN, $month, $year); //當(dāng)月最后一天 $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次,響應(yīng)時間會大大提高。
注意:
1.由于需查詢當(dāng)月所有數(shù)據(jù),在數(shù)據(jù)量過大時,不宜采取本方法。
2.為避免當(dāng)天沒有數(shù)據(jù)而造成的數(shù)據(jù)缺失,在查詢后,理應(yīng)根據(jù)需求對數(shù)據(jù)進行處理。
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php+mysql數(shù)據(jù)庫操作入門教程》、《php+mysqli數(shù)據(jù)庫程序設(shè)計技巧總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設(shè)計有所幫助。
標(biāo)簽:宿遷 延安 澳門 深圳 宜春 工商登記 佛山 常德
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《PHP+MySQL實現(xiàn)對一段時間內(nèi)每天數(shù)據(jù)統(tǒng)計優(yōu)化操作實例》,本文關(guān)鍵詞 PHP+MySQL,實現(xiàn),對,一段,時,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。