本文实例讲述了PHP+MySQL实现对一段时间内每天数据统计优化操作。分享给大家供大家参考,具体如下:

在互联网项目中,对项目的数据分析必不可少。通常会统计某一段时间内每天数据总计变化趋势调整营销策略。下面来看以下案例。

案例

在电商平台中通常会有订单表,记录所有订单信息。现在我们需要统计某个月份每天订单数及销售金额数据从而绘制出如下统计图,进行数据分析。

订单表数据结构如下:

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程序设计有所帮助。