MySQL 對一段時間內每天數據統計案例--sql優化

在互聯網項目中,對項目的數據分析必不可少。通常會統計某一段時間內每天數據總計變化趨勢調整營銷策略。下面來看以下案例。

案例

在電商平臺中通常會有訂單表,記錄所有訂單信息。現在我們需要統計某個月份每天訂單數及銷售金額數據從而繪製出如下統計圖,進行數據分析。

這裏寫圖片描述

訂單表數據結構如下:

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.爲避免當天沒有數據而造成的數據缺失,在查詢後,理應根據需求對數據進行處理。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章