2016-11-27 112 views
0

我試圖重構我的代碼。我返回所有行,並用php過濾結果集,但這很快就會成爲性能問題。在SQL命令中計算百分比

當前代碼:

$percentOff = 80; 

$stmt = $this->dbh->prepare("SELECT * FROM products WHERE Available=1 AND Merchant='Amazon'"); //Selects all from DB. VERY slow 

      $finalResults = array(); 
      //Limit the results returned 
      foreach($rows as $row){ 
       $totalSavings = ($row["LowestNewPrice"] - $row["LowestUsedPrice"])/$row["LowestNewPrice"] * 100; 
       if($totalSavings >= $percentOff){ 
        $finalResults[] = $row; 
       } 
      } 

重構的SQL:

$stmt = $this->dbh->prepare("SELECT * FROM products WHERE Available=1 AND Merchant='Amazon' AND (LowestNewPrice - LowestUsedPrice/LowestNewPrice * 100) >= ?"); 
$stmt->bindValue(1, $percentOff, PDO::PARAM_STR); 

這將返回所有的products。我只想返回> = 80的結果。我哪裏錯了?

各地LowestNewPrice - LowestUsedPrice

  • 路加福音提到的DB

    | LowestNewPrice   | int(11)  | NO |  | NULL    |  | 
    | LowestUsedPrice   | int(11)  | NO |  | NULL    |  | 
    
  • +1

    根據規模,可能值得在列中緩存「(LowestNewPrice - LowestUsedPrice/LowestNewPrice * 100)'。作爲一個快速猜測,這可能是'LowestUsedPrice/LowestNewPrice'的整數除法的結果。這取決於你的表格模式。 –

    +0

    緩存是在計劃中,但我需要首先得到這個簡單的修復。我對MySQL不太熟悉,整數除法如何影響聲明? PHP正在處理它,這只是緩慢的 –

    +0

    Interger劃分舍入到最接近的整數。所以例如(48/50)* 100 = 0 * 100 = 0評估爲48/50 * 100,而100 * 48/50評估爲(100 * 48)/ 50 = 4800/50 = 96。 –

    回答

    1
    1. 你缺少括號,你也可能會運行到整數除法。在之前乘以100