我正在使用 PHP/MySQL
我有大约 2,000 种产品。我必须计算每种产品过去 6、3、1 个月的平均月销售额,并立即在页面中显示...
目前我有以下代码(每个产品的循环):
$past_month_sales = $this->SalesPerProduct->getSalesForMonthYear( $acc_code,
$item_code, $past_month[0],
$past_month[1] );
$past_two_months_sales = $this->SalesPerProduct->getSalesForMonthYear( $acc_code,
$item_code, $past_two_months[0],
$past_two_months[1] );
$past_three_months_sales = $this->SalesPerProduct->getSalesForMonthYear( $acc_code,
$item_code, $past_three_months[0],
$past_three_months[1] );
$past_four_months_sales = $this->SalesPerProduct->getSalesForMonthYear( $acc_code,
$item_code, $past_four_months[0],
$past_four_months[1] );
$past_five_months_sales = $this->SalesPerProduct->getSalesForMonthYear( $acc_code,
$item_code, $past_five_months[0],
$past_five_months[1] );
$past_six_months_sales = $this->SalesPerProduct->getSalesForMonthYear( $acc_code,
$item_code, $past_six_months[0],
$past_six_months[1] );
//for past 3 months
if( $past_month_sales == 0
|| $past_two_months_sales == 0
|| $past_three_months_sales == 0){
$past_three_sales_ave = "n/a";
}else{
$past_three_sales_ave = round( ( $past_month_sales
+ $past_two_months_sales
+ $past_three_months_sales )
/ 3 );
}
//for past 6 months
if( $past_month_sales == 0
|| $past_two_months_sales == 0
|| $past_three_months_sales == 0
|| $past_four_months_sales == 0
|| $past_five_months_sales == 0
|| $past_six_months_sales == 0){
$past_six_sales_ave = "n/a";
}else{
$past_six_sales_ave = round( ( $past_month_sales
+ $past_two_months_sales
+ $past_three_months_sales
+ $past_four_months_sales
+ $past_five_months_sales
+ $past_six_months_sales )
/ 6 );
}
但是上面的代码很慢,即使是 100 个产品也需要很长时间才能加载......
我的 getSalesForMonthYear 函数如下所示:
function getSalesForMonthYear( $account_code, $item_code, $month, $year ){
$sql = "select
SalesPerProduct.sales_value
from
sales_per_products as SalesPerProduct
where
account_code = '{$account_code}' and
item_code = '{$item_code}' and
month = '{$month}' and
year = '{$year}'";
$val = $this->query($sql);
if( empty( $val[0]['SalesPerProduct']['sales_value'] ) ){
$val = 0;
}else{
$val = $val[0]['SalesPerProduct']['sales_value'];
}
return $val;
}
知道这怎么能快吗?蒂亚!!!