我正在尝试重构我的代码。我正在返回所有行,并使用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 | |
答案 0 :(得分:1)
LowestNewPrice - LowestUsedPrice