0

我有一个用 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"];

}

}

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

提前致谢。

史蒂芬

4

1 回答 1

0

这是您的查询:

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 不能使用索引。

于 2013-09-10T11:33:59.693 回答