【问题标题】:Making sales statistics for my ERP system, but performance is bad为我的 ERP 系统做销售统计,但性能很差
【发布时间】:2013-09-10 11:31:29
【问题描述】:

我有一个用 PHP 编写的带有 mySQL 数据库的 ERP 系统,其中包含我过去 4 年的所有订单。现在我想做一个函数来生成销售统计。应该可以设置搜索条件,如销售员、部门和年份/期间。

销售统计数据应按客户分组。就像这个链接上的插图: http://maabjerg.eu/illustration_stat.png

我的客户表:

customers
--------------------
id - int - auto - primary
name - varchar(100)

我的订单表:

orders
-------------------
id - int - auto - primary
customerId - int
departmentId - int
salesmanId - int
orderdate - datetime
invoicedate - datetime
quantity - int
saleprice - decimal(10,2)

我做这个没问题,但性能很差。我之前的做法是这样的:

foreach($customers as $customer)
{

foreach($months as $month)
{
    $sql = mysql_query("select sum(quantity*saleprice) as amount from orders where DATE_FORMAT(invoicedate, '%m-%Y') = '".$month."-".$_REQUEST["year"]."' AND customerId='".$customer->id."'",$connection) or die(mysql_error());
$rs = mysql_fetch_assoc($sql);

$result[$customerId][$month] = $rs["amount"];

}

}

我希望有人可以给我建议如何使这成为最好的方法。

提前致谢。

史蒂芬

【问题讨论】:

  • 为什么不将其全部作为单个 SQL 查询运行?
  • 做一个EXPLAIN 看看是否有机会添加索引。

标签: php mysql sql table-statistics


【解决方案1】:

这是您的查询:

select sum(quantity*saleprice) as amount
from order
where DATE_FORMAT(invoicedate, '%m-%Y') = '".$month."-".$_REQUEST["year"]."' AND 
      customerId='".$customer->id."'

如前所述,如果您想加快速度,请在order(customerId) 上添加索引。

您也应该将其作为一个查询来执行:

select c.name, sum(quantity*saleprice) as amount
from customers c left outer join
     order o
     on c.id = o.customerId
where DATE_FORMAT(invoicedate, '%m-%Y') = '".$month."-".$_REQUEST["year"]."' AND 
      customerId='".$customer->id."'
group by c.name;

您可以稍微重写查询,并在order(customerId, invoicedate) 上建立索引。这需要为周期的开始和结束创建常量,然后执行以下操作:

select c.name, sum(quantity*saleprice) as amount
from customers c left outer join
     order o
     on c.id = o.customerId
where invoicedate $StartDate and $EndDate AND 
      customerId='".$customer->id."'
group by c.name;

当列上有函数调用时,MySQL 不能使用索引。

【讨论】:

    猜你喜欢
    • 2015-09-24
    • 2014-10-23
    • 1970-01-01
    • 2021-03-23
    • 2019-12-15
    • 2011-12-24
    • 2012-12-10
    • 1970-01-01
    • 2014-04-12
    相关资源
    最近更新 更多