计算SQL命令中的百分比

时间:2016-11-27 07:53:25

标签: php mysql sql database

我正在尝试重构我的代码。我正在返回所有行,并使用php过滤结果集,但这很快成为性能问题。

当前代码:

$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返回ALL。我只想返回> = 80的结果。我哪里出错?

DB

| LowestNewPrice           | int(11)      | NO   |     | NULL                |       |
| LowestUsedPrice          | int(11)      | NO   |     | NULL                |       |

1 个答案:

答案 0 :(得分:1)

  1. LowestNewPrice - LowestUsedPrice
  2. 周围缺少括号
  3. 正如卢克所说,你也可能遇到整数分裂。乘以100 之前除以。