使用PDO在循环中优化多个MySQL查询

时间:2013-01-18 15:38:07

标签: php mysql optimization pdo

考虑以下代码片段,其中有两个MySQL查询作为循环的一部分被触发:

<?php
    $requested_names_array = ['ben','john','harry'];

    $statement_1 = $connection->prepare("SELECT `account_number` FROM `bank_members` WHERE `name` = :name");
    $requested_name = "";
    $statement_1->bindParam(":name",$requested_name); //$requested_name will keep changing in value in the loop below

    foreach($requested_names_array as $requested_name){
        $execution_1 = $statement_1->execute();
        if($execution_1){
            //fetch and process results of first successful query
            $statement_2 = $connection->prepare("SELECT `account_balance` from `account_details` WHERE `account_number` = :fetched_account_number");
            $statement_2->bindValue(":fetched_account_number",$fetched_account_number);
            $execution_2 = $statement_2->execute();
            if($execution_2){
                //fetch and process results of second successful query, possibly to run a third query
            }
        }else{
            echo "execution_1 has failed, $statement_2 will never be executed.";
        }
    }
?>

这里的问题是 $ statement_2一次又一次地准备,而不仅仅是用不同的参数执行。

我不知道在进入循环之前是否还可以准备$ statement_2,因此它只会执行(而不是准备),因为它的参数在循环中被更改,就像$ statement_1一样。

在这种情况下,你最终会先准备几个语句,每个语句都要在后面的循环中执行。

即使这是可能的,也可能效率不高,因为如果其他语句的执行失败,某些语句将被徒劳地准备。

您如何建议优化这样的结构?

1 个答案:

答案 0 :(得分:2)

您应该重写为联接:

SELECT account_number, account_balance
FROM bank_members
INNER JOIN account_details ON bank_members.account_number = account_details.account_number

一个查询,准备一次,执行一次,获取所需的所有数据。