這次給大家?guī)鞵HP+MySQL定時數(shù)據(jù)統(tǒng)計優(yōu)化,PHP+MySQL定時數(shù)據(jù)統(tǒng)計優(yōu)化的注意事項有哪些,下面就是實戰(zhàn)案例,一起來看一下。
在互聯(lián)網(wǎng)項目中,對項目的數(shù)據(jù)分析必不可少。通常會統(tǒng)計某一段時間內(nèi)每天數(shù)據(jù)總計變化趨勢調(diào)整營銷策略。下面來看以下案例。
案例
在電商平臺中通常會有訂單表,記錄所有訂單信息?,F(xiàn)在我們需要統(tǒng)計某個月份每天訂單數(shù)及銷售金額數(shù)據(jù)從而繪制出如下統(tǒng)計圖,進行數(shù)據(jù)分析。
訂單表數(shù)據(jù)結構如下:
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ù),總金額應當如何做呢?
一般方法
首先最容易想到的方法,先利用 php 函數(shù) cal_days_in_month() 獲取當月天數(shù),然后構造一個當月所有天的數(shù)組,然后在循環(huán)中查詢每天的總數(shù),構造新數(shù)組。
代碼如下:
$month = '04'; $year = '2017'; $max_day = cal_days_in_month(CAL_GREGORIAN, $month, $year); //當月最后一天 //構造每天的數(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ōu)化
如何使用一個sql直接查詢出各天的數(shù)量總計呢?
此時需要利用 mysql 的 date_format 函數(shù),在子查詢中先查出當月所有訂單,并將 enterdate 用 date_format 函數(shù)轉(zhuǎn)換為 天 ,然后按天 group by 分組統(tǒng)計。 代碼如下:
$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);
相信看了本文案例你已經(jīng)掌握了方法,更多精彩請關注php中文網(wǎng)其它相關文章!
推薦閱讀:
立即學習“PHP免費學習筆記(深入)”;
以上就是PHP+MySQL定時數(shù)據(jù)統(tǒng)計優(yōu)化的詳細內(nèi)容,更多請關注php中文網(wǎng)其它相關文章!
PHP怎么學習?PHP怎么入門?PHP在哪學?PHP怎么學才快?不用擔心,這里為大家提供了PHP速學教程(入門到精通),有需要的小伙伴保存下載就能學習啦!
Copyright 2014-2025 http://www.miracleart.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號