我有一个正在处理的时间相关脚本,并使用 microtime() 找到了瓶颈。我确定时间增加是由于对 300 多个值进行检查以查看它们是否一次一个地存在于数据库中造成的,查询时间为 0.04 秒。
脚本的背景是缓存脚本。我需要查看它是否存在于数据库中,因此我需要一个 true/false(由 rowCount 获得),但我还需要一种将 false 与值相关联的方法,以便我可以更新它。我知道在 (:ARRAY) 中使用 WHERE 标记会比单独调用更快,但我想不出一种方法可以在此方法中将 true/false 关联应用于值。
我当前的代码如下:
//loop through all our values!
//prepare out reusuable statement
$stmt = $db->prepare("SELECT * from cache WHERE value=?");
foreach($values as $tempVal)
{
//find if its in the database
try
{
$stmt->execute(array($tempVal));
$valCount = $stmt->rowCount();
} catch(PDOException $ex) {
echo "PDO error send this to us: " . $ex->getMessage();
}
//update flag
$addToUpdate = 1;
//if its in the database
if($valCount > 0)
{
//get the tag data
$valRes= $stmt->fetch();
//check if cache expired
$addToUpdate = 0;
}
//add to update list
if($addToUpdate)
{
//needs updating
$updateList[] = $tempVal;
//add to not in DB list to minimize queries
if($tagTCount == 0)
{
$notInDB[$tempVal] = $tempVal;
}
}
有什么建议吗?如果有什么不清楚的,我可以解释更多。
谢谢, 尼克
最佳答案
因此,您只需使用 IN (?,?,?,?,?...)
列表对完整数组发出查询:
// abstract, use a PDO wrapper of your choosing
$query = db("SELECT * FROM cache WHERE value IN (??)", $values);
然后遍历结果列表。只有匹配的 $values 才会返回。因此,从中构建您的第一个列表:
foreach ($query as $row) {
$updateList[] = $row["value"];
}
要获得缺失条目的列表,只需 diff那对你原来的数组:
$notInDB = array_diff($values, $updateList);
您当然可以使用第二个 NOT IN
查询。但是在 PHP 中进行区分更简单。
关于php - PDO检查数据库中是否存在300多个值的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12273926/