mysql - 跨表获取 mysql 中的总销售额数据。查询超时
问题描述
获取总销售额数据。
我在 Godaddy 上托管了一个 mysql 数据库,其中包含下表。
- Customer_data - 客户代码、姓名等(约 450 行)
- 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 |
+---------------+--------+--------+--------+--------+--------+--------+
.....
我试过这样做 -
- 带有循环json的php-查询超时,因为要处理的数据太多
- 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++;
}
解决方案
该表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)|...'"
推荐阅读
- c++ - C++:如何返回指向非静态成员函数的指针?
- python - (Python)有没有办法分解脚本,以便输出可以用作同一脚本中另一个 UDF 的输入?
- javascript - 理解“this”绑定
- python - 自动将信息从 Dictionary 传输到 Anki
- android - 第一次在 ViewPager2 中滚动没有动画
- python - Pandas html 到 df - 数字中的逗号
- flutter - Flutter:列表视图中最喜欢的项目
- python - Python docx:如何从多个单词文件中提取两个固定字符串之间的表
- layout - 如何在 QML 中关闭带有特定按钮/区域的抽屉弹出窗口?
- php - 如何在宅基地机器上和本地服务时显示相同的 Laravel 路线