php mysql 统计_PHP和MySQL实现优化统计每天数据
在互聯網項目中,對項目的數據分析必不可少。通常會統計某一段時間內每天數據總計變化趨勢調整營銷策略。下面來看以下案例。
案例
在電商平臺中通常會有訂單表,記錄所有訂單信息。現在我們需要統計某個月份每天訂單數及銷售金額數據從而繪制出如下統計圖,進行數據分析。
訂單表數據結構如下:order_idorder_sntotal_priceenterdate25396A4E610E250C2D378D7EC94179E14617F2306.002017-04-01 17:23:26
25397EAD217C0533455EECDDE39659ABCDAE917.902017-04-01 22:15:18
25398032E6941DAD44F29651B53C41F6B48A0163.032017-04-02 07:24:36
此時查詢某月各天下單數,總金額應當如何做呢?
一般方法
首先最容易想到的方法,先利用 php 函數
代碼如下:
$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 的 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 mysql 统计_PHP和MySQL实现优化统计每天数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: hive 十六进制转十进制_hive 常
- 下一篇: 怎样在电脑上上传图片_电脑上回收站怎样恢