首页 > 解决方案 > 跨表获取 mysql 中的总销售额数据。查询超时

问题描述

获取总销售额数据。

我在 Godaddy 上托管了一个 mysql 数据库,其中包含下表。

  1. Customer_data - 客户代码、姓名等(约 450 行)
  2. delivery_data - 日期、发票编号、数量等(每月约 800 行)

我需要获得一个月内所有客户的总销售数据。(理想情况下,不同的月份范围将由用户输入以分析趋势)。

+---------------+--------+--------+--------+--------+--------+--------+
| Customer Name | Jan-18 | Feb-18 | Mar-18 | Apr-18 | May-18 | Jun-18 |
+---------------+--------+--------+--------+--------+--------+--------+
| ABC           |   30   |   50   |   30   |   80   |   70   |  140   |
+---------------+--------+--------+--------+--------+--------+--------+
| DEF           |   40   |   50   |   130  |  180   |   70   |  140   |
+---------------+--------+--------+--------+--------+--------+--------+
.....

我试过这样做 -

  1. 带有循环json的php-查询超时,因为要处理的数据太多
  2. Excel VBA - 在服务器上运行查询需要几个小时,所有其他操作都会停止。

以更有效的方式获取这些数据的最佳方式是什么?

编辑 1 -

SQL查询

while ($year<2017){
    $months=0;
    while ($months<12){
        $cust_code=mysql_result($result2,$no,"code");
        $sqlquery3="select ifnull(sum(a.quantity),0) as total_quantity
                from delivery_line a, delivery_main b 
            where 
                a.item REGEXP 'INDOX|MEDOX|INDNIT|INDCO2|ARGON'
                and a.del_no=b.no 
                and a.series=b.series
                and b.cust_code='$cust_code'
                and month(b.date_added)=($months+1)
                and year(b.date_added) = ($year)";
        $result3=mysql_query($sqlquery3);
        $count3=mysql_num_rows($result3);
        $quantity=mysql_result($result3,0,"total_quantity");
        echo "<td>".$quantity."</td>";
    $months++;
    }
    $year++;
}

标签: mysql

解决方案


该表delivery_data需要有一个外键引用customer_data,然后您只需

SELECT * from delivery_data a INNER JOIN customer_data b WHERE
a.custcode = b.custcode AND MONTH(b.date) = 5;

其中数字 5 是五月。

确保在要加入或用作条件的列上设置了正确的索引。即a.del、b.no、a.series、b.series、b.cust_code、b.date_added。

a.item 上的正则表达式可能是杀手,但索引不会对你有任何好处,除非你可以利用字段的开头作为锚点,即

"LIKE 'NEEDLE%'" 

或者

"REGEXP '^(NEEDLE)|...'"

推荐阅读