尝试消除临时表MYSQL并尽可能将进程合并到一个语句中

时间:2017-07-31 12:11:27

标签: php mysql performance temp-tables

我有一个应用程序跟踪11名销售人员的销售情况。这是一个足够简单的过程,除了销售人员可以分享销售额,将销售价格减半。这意味着如果两个销售人员共享一个价值100美元的工作,那么每个销售人员只为自己计算50美元的销售价值。下面是我目前用来完成这个过程的代码,但它看起来很笨重,而且性能有点迟钝。是否可以将它组合成一个单独的过程并且不需要临时表(我也看到了你不应该在生产中使用临时表的地方)

$sql = "DROP TEMPORARY TABLE IF EXISTS newbalancetbl" ;
  mysqli_query ($db, $sql ) or ( "Error " . mysqli_error () ) ;

  $newBalances = "
    CREATE TEMPORARY TABLE newbalancetbl (
      `custid` int NOT NULL,
      `assigned` int NOT NULL,
      `newBalance` double,
      PRIMARY KEY(custid)
    )
  ";

   mysqli_query($db, $newBalances) or die ("Sql error : ".mysqli_error());

  $year = date("Y");
  $start = "01/01/".$year;
  $today = date("Y-m-d");
  $first = $year."-01-01";

  $assignments = "SELECT leadid, price
                  FROM jobbooktbl 
                  WHERE convertdate >= '".$first."' AND convertdate<='".$today."' AND (status=4 OR status=6 OR status=7 OR status=8 OR status=11)";
  $assignmentsqry = mysqli_query($db,$assignments);
  while ($row = mysqli_fetch_array($assignmentsqry)) {
    $custid = $row["leadid"];
    $price = $row["price"];

    $statement = $db->prepare("INSERT INTO newbalancetbl (custid, newBalance) VALUES (?,?)");
    $statement->bind_param('id', $custid, $price);
    $statement->execute();
  }

  $sqlnewbal = "SELECT a.custid, COUNT(a.custid) AS assCnt
                  FROM assignmentstbl a, newbalancetbl b
                  WHERE a.custid=b.custid
                  GROUP BY a.custid";
  $qrynewbal = mysqli_query($db,$sqlnewbal);
  while ($row = mysqli_fetch_array($qrynewbal)) {
    $custid = $row['custid'];
    // $paid = $row["sumAmnt"];
    $assigned = $row['assCnt'];

    $usqlUpdate = $db->prepare("UPDATE newbalancetbl SET assigned=? WHERE custid=?");
    $usqlUpdate->bind_param('ii',$assigned,$custid);
    $usqlUpdate->execute();
  }

  $sqlnewbal = "SELECT *
                  FROM newbalancetbl";
  $qrynewbal = mysqli_query($db,$sqlnewbal);
  while ($row = mysqli_fetch_array($qrynewbal)) {
    $custid = $row['custid'];
    $assigned = $row['assigned'];
    $newBalance = $row['newBalance'];
    $newBal = $newBalance/$assigned;
    $newBal - number_format($newBal,2);

    $usqlUpdate = $db->prepare("UPDATE newbalancetbl SET newBalance=? WHERE custid=?");
    $usqlUpdate->bind_param('di',$newBal,$custid);
    $usqlUpdate->execute();
  }

  $salesArray = [];

  $tesql = "SELECT SUM(n.newBalance) AS newB, u.username
            FROM newbalancetbl n
            INNER JOIN assignmentstbl a 
              ON a.custid=n.custid 
            INNER JOIN usertbl u 
              ON a.userid=u.userid 
            -- WHERE u.salesman=1
            GROUP BY a.userid
            ORDER BY newB DESC";
  $teresult = mysqli_query($db,$tesql);
  while ($row = mysqli_fetch_array($teresult)) {
    $user = $row['username'];
    $sales = $row['newB'];

    array_push($salesArray, [$user,floatval($sales)]);
  }

  $arrayCount = count($salesArray);

  $total_sales = 0;
  $total_sales = array_sum( array_map(function($element){
                  return $element[1];
                }, 
             $salesArray));
  $pretotal_sales = number_format($total_sales, 2);
  $total_sales = '$' . number_format($total_sales, 2);

表架构:

jobbooktbl enter image description here

assignmentstbl enter image description here

3 个答案:

答案 0 :(得分:1)

我将通过代码了解它的作用,并建议修改。

CREATE TEMPORARY TABLE newbalancetbl (
  custid     int NOT NULL,
  assigned   int NOT NULL,
  newBalance double,
  PRIMARY KEY(custid)
) ENGINE=Memory

行。该表似乎很小,因此您可能希望使用ENGINE = Memory来加快速度。另外,请考虑使用DECIMAL类型而不是DOUBLE。这不是强制性的,但它避免了舍入错误的麻烦。

反正。你的第一个查询。使用php while()循环填充表格是缓慢且不必要的。只需:

INSERT INTO newbalancetbl (custid, newBalance)
SELECT leadid, price
FROM jobbooktbl 
WHERE convertdate BETWEEN '$first' AND '$today' 
AND status IN (4,6,7,8,11);

注意使用IN()更易读。另外,BETWEEN。 INSERT INTO SELECT将比在php中循环查询结果快得多。另外,我没有在插入的列中看到“assigned”和“newBalance”,但表中没有指定任何默认值。您应该明确默认值。

现在,下一个查询是:

SELECT custid, COUNT(*) AS assCnt
FROM assignmentstbl a JOIN newbalancetbl b USING (custid)
GROUP BY custid

我用正确的语法改变了丑陋的旧JOIN语法(从大约1999年开始)。此外,COUNT(col)计算“col”不为空的行。所以COUNT(a.custid)暗示“a.custid”实际上可以为null。由于它不能,这种语法只是令人困惑。我用count(*)替换它。

然后你在PHP中查看结果,然后执行“UPDATE newbalancetbl SET assign = $ assCnt WHERE custid =?”

您应该决定是使用名称“assCnt”还是“已分配”。我更喜欢第一个,因为它是一个计数,名称中有“cnt”使它更容易混淆。现在,这个循环是不必要的,我们可以使用带有JOIN的单个UPDATE,或者更好,从一开始就将值构建到rable中。因此,第一个查询变为:

INSERT INTO newbalancetbl (custid, newBalance, assigned)
SELECT j.leadid, j.price, 
    (SELECT count(*) FROM assignmentstbl a WHERE a.custid=j.leadid) AS assigned
FROM jobbooktbl j
WHERE j.convertdate BETWEEN '$first' AND '$today' 
AND j.status IN (4,6,7,8,11);

我使用了一个子选择。请随意使用JOIN。

下一个查询。我会忽略“$ newBal - number_format($ newBal,2);”因为你使用“ - ”代替“=”而什么都不做......这可以通过使用NUMERIC格式来解决,或者只是使用它:

UPDATE newbalancetbl 
SET newBalance=ROUND(newBalance/assigned, 2)

消除了另一个php循环。但是我们可以在我们处理它的同时消除更新和临时表。

SELECT 
    j.leadid AS custid, 
    ROUND( j.price / (SELECT count(*) FROM assignmentstbl a WHERE a.custid=j.leadid), 2) AS newBalance
FROM jobbooktbl j
WHERE j.convertdate BETWEEN '$first' AND '$today' 
AND j.status IN (4,6,7,8,11);

这应该给出与临时表所包含的结果完全相同的结果,减去“已分配”列,但无论如何都不会在代码的其余部分中使用,因此我们可以删除它。现在,让我们将其插入下一个查询...

SELECT ROUND(SUM(n.newBalance), 2) AS newB, u.username
FROM (
    SELECT 
        j.leadid AS custid, 
        j.price / (SELECT count(*) FROM assignmentstbl a WHERE a.custid=j.leadid) AS newBalance
    FROM jobbooktbl j
    WHERE j.convertdate BETWEEN '$first' AND '$today' 
    AND j.status IN (4,6,7,8,11)
    ) n
    JOIN assignmentstbl a USING (custid)
    JOIN usertbl u USING (userid)
    -- WHERE u.salesman=1
    GROUP BY a.userid
    ORDER BY newB DESC

这应该做你想要的。我在外部查询中移动了ROUND。

答案 1 :(得分:1)

假设总是有人分配给这份工作,而且许多其他人暗示问题,单一查询可能是:

SELECT SUM(n.newBalance) AS newB, u.username, u.userid
FROM 
    (SELECT 
        j.leadid as custid,
        (j.price / COUNT(*)) as newBalance
    FROM jobbooktbl j
    INNER JOIN assignmentstbl a 
      ON a.custid = j.leadid
    WHERE j.convertdate >= ? 
      AND j.convertdate <= ? 
    GROUP BY 1
    ) n
INNER JOIN assignmentstbl a 
  ON a.custid=n.custid 
INNER JOIN usertbl u 
  ON a.userid=u.userid 
GROUP BY u.userid
ORDER BY newB DESC;

n子查询计算平均价格

  

如果他们是工作中唯一的推销员而且工作是200美元,那么如果他们与另一位推销员分享工作,那么他们将被记入200美元(200/1 = 200),这意味着有两个推销员被分配然后他们只会100美元(200/2 = 100)

假设如果有4名销售人员分配到同一份工作,他们每人将获得50美元。

答案 2 :(得分:0)

只是有点刺伤这个

SELECT name,SUM(
     SELECT  (
         SELECT price/
         (SELECT COUNT(1) FROM jobs WHERE job.ID = Assignments.jobId) 
               FROM jobs WHERE 
                   (SELECT COUNT(1) FROM assignment WHERE salesman.ID = assignment.salesmanId) > 0)
      )
    ) AS commission 
    FROM salesman.

对,所以选择所有的销售人员,从他所属的所有工作中获得价格。将该价格除以工作人数。该表可能已更改名称,但总的来说,我认为这就是您想要的。