在互聯(lián)網(wǎng)項(xiàng)目中瞎惫,對(duì)項(xiàng)目的數(shù)據(jù)分析必不可少盐股。通常會(huì)統(tǒng)計(jì)某一段時(shí)間內(nèi)每天數(shù)據(jù)總計(jì)變化趨勢(shì)調(diào)整營銷策略驮审。下面來看以下案例鲫寄。
案例
在電商平臺(tái)中通常會(huì)有訂單表,記錄所有訂單信息》枰現(xiàn)在我們需要統(tǒng)計(jì)某個(gè)月份每天訂單數(shù)及銷售金額數(shù)據(jù)從而繪制出如下統(tǒng)計(jì)圖地来,進(jìn)行數(shù)據(jù)分析。
訂單表數(shù)據(jù)結(jié)構(gòu)如下:
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í)查詢某月各天下單數(shù)熙掺,總金額應(yīng)當(dāng)如何做呢未斑?
一般方法
首先最容易想到的方法,先利用 php 函數(shù) cal_days_in_month() 獲取當(dāng)月天數(shù)币绩,然后構(gòu)造一個(gè)當(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;
這個(gè)sql簡單芽突,但是每次需要進(jìn)行30次查詢請(qǐng),嚴(yán)重拖慢響應(yīng)時(shí)間董瞻。
優(yōu)化
如何使用一個(gè)sql直接查詢出各天的數(shù)量總計(jì)呢寞蚌?
此時(shí)需要利用 mysql 的 date_format 函數(shù),在子查詢中先查出當(dāng)月所有訂單钠糊,并將 enterdate 用 date_format 函數(shù)轉(zhuǎn)換為 天 挟秤,然后按天 group by 分組統(tǒng)計(jì)。 代碼如下:
$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)時(shí)間會(huì)大大提高。
注意:
1.由于需查詢當(dāng)月所有數(shù)據(jù)截珍,在數(shù)據(jù)量過大時(shí)昔脯,不宜采取本方法。
2.為避免當(dāng)天沒有數(shù)據(jù)而造成的數(shù)據(jù)缺失笛臣,在查詢后云稚,理應(yīng)根據(jù)需求對(duì)數(shù)據(jù)進(jìn)行處理。