PDO检查数据库中是否存在300+个值的最佳方式


PDO best way to check if 300+ values exist in database

我正在编写一个与时间相关的脚本,并使用microtime()找到瓶颈。我确定时间增加的原因是对300多个值进行检查,看看它们是否存在于数据库中,每次查询0.04秒。

脚本的背景是它是一个缓存脚本。我需要看看它是否存在于数据库中,所以我需要一个true/false(通过rowCount获得),但我也需要一种将false与值关联的方法,这样我就可以更新它。我知道使用WHERE标记in(:ARRAY)会比单个调用工作得更快,但我想不出用这种方法将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;
        }
    }   

有什么建议吗?如果有什么不清楚的地方,我可以解释更多。

谢谢,Nick

因此,您只需使用IN (?,?,?,?,?...)列表发出带有完整数组的查询:

// abstract, use a PDO wrapper of your choosing
$query = db("SELECT * FROM cache WHERE value IN (??)", $values);

然后对结果列表进行迭代。只有匹配的$值才会返回。因此,建立你的第一个列表:

foreach ($query as $row) {
     $updateList[] = $row["value"];
}

要获得缺席条目的列表,只需将其与原始数组进行比较:

$notInDB = array_diff($values, $updateList);

当然,您可以使用第二个NOT IN查询。但是在PHP中进行差异化比较简单。