0

任务:查找每个销售人员每个月销售的总产品数量并制作报告。我为销售人员使用了一个外部循环,对每个销售人员使用了一个 SUM() 查询 12 次的内部循环,同时将数据存储在一个多维数组中,即,对于每个销售人员索引,我打算为 12 个月的销售存储 12 个索引值.

问题:当我在内部循环中使用查询时,它没有显示汇总 product_quantity 列。当我在循环外对特定 id 和月份使用查询时,查询会正确汇总该月的销售额。所以,乳清是查询在内部循环中不起作用。是不是因为为每个销售人员调用 12 次查询导致流程效率低下?有更好的方法吗?

            while($salesperson=mysql_fetch_array($qry1))
        {
            $postData[$i]=$salesperson['name'];
            echo $postData[$i];
            echo "</br> ";
            $m=1;
          while($m<=3)
            {
                $qry2=mysql_query("Select SUM(addsales.product_quantity) AS Total from addsales where sid='".$salesperson['sid']."' AND month='".$m."'");
                echo $qry2;
                echo "</br>";
                $total=mysql_fetch_array($qry2);

                    if($total['Total']!=0)
                    {
                        $postData[$i][$m]=$total['Total'];
                        echo $postData[$i][$m];
                    }
                    else
                    {    $postData[$i][$m]=0;
                    echo $postData[$i][$m];}


                $m++;
                echo "</br>";
            }
            $size--;
            $i++;
        }
        echo "</br>";

        mysql_close($con);

        $i=1;

?>
4

1 回答 1

0

从数据库的角度来看,外部和内部循环效率低下,因为当您发送更接近您实际想要的 SQL 查询时,可以通过更少的数据库往返来实现相同的结果。

SELECT s.sid, s.name, 
(SELECT SUM(a1.product_quantity) FROM addsales a1 
 WHERE a1.sid = s.sid AND a1.month = '1'
) AS month1sold,
(SELECT SUM(a2.product_quantity) FROM addsales a2 
 WHERE a2.sid = s.sid AND a2.month = '2'
) AS month2sold,
(SELECT SUM(a3.product_quantity) FROM addsales a3 
 WHERE a3.sid = s.sid AND a3.month = '3'
) AS month3sold,
(SELECT SUM(a4.product_quantity) FROM addsales a4 
 WHERE a4.sid = s.sid AND a4.month = '4'
) AS month4sold,
(SELECT SUM(a5.product_quantity) FROM addsales a5 
 WHERE a5.sid = s.sid AND a5.month = '5'
) AS month5sold,
(SELECT SUM(a6.product_quantity) FROM addsales a6 
 WHERE a6.sid = s.sid AND a6.month = '6'
) AS month6sold,
(SELECT SUM(a7.product_quantity) FROM addsales a7 
 WHERE a7.sid = s.sid AND a7.month = '7'
) AS month7sold,
(SELECT SUM(a8.product_quantity) FROM addsales a8
 WHERE a8.sid = s.sid AND a8.month = '8'
) AS month8sold,
(SELECT SUM(a9.product_quantity) FROM addsales a9 
 WHERE a9.sid = s.sid AND a9.month = '9'
) AS month9sold,
(SELECT SUM(a10.product_quantity) FROM addsales a10 
 WHERE a10.sid = s.sid AND a10.month = '10'
) AS month10sold,
(SELECT SUM(a11.product_quantity) FROM addsales a11 
 WHERE a11.sid = s.sid AND a11.month = '11'
) AS month11sold,
(SELECT SUM(a12.product_quantity) FROM addsales a12 
 WHERE a12.sid = s.sid AND a12.month = '12'
) AS month12sold
FROM salesperson s
WHERE ....
于 2012-09-06T06:14:42.753 回答