doumicheng6732 2013-01-18 15:38
浏览 29
已采纳

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

Consider the following code snippet which has two MySQL queries being fired as part of a loop:

<?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.";
        }
    }
?>

The problem here is that $statement_2 is prepared time and time again, instead of merely being executed with different parameters.

I don't know if $statement_2 could also be prepared before entering the loop, so it is only executed (and not prepared) as its parameters are changed in the loop, as happens with $statement_1.

In that case, you'd end up with several statements being prepared first, each of them to be executed in the loop that follows.

Even if that would be possible, it might not be efficient, for some statements would be prepared in vain in case the execution of other statements fails.

How would you recommend keeping such a structure optimized?

  • 写回答

1条回答 默认 最新

  • doushao8399 2013-01-18 15:42
    关注

    You should re-write as a join:

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

    one single query, prepared once, executed once, fetching all the data you need.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 socket通信实现多人聊天室疑惑
  • ¥15 DEV-C++编译缺失
  • ¥33 找熟练码农写段Pyhthon程序
  • ¥100 怎么让数据库字段自动更新
  • ¥15 antv g6 力导向图布局
  • ¥15 quartz框架,No record found for selection of Trigger with key
  • ¥15 锅炉建模+优化算法,遗传算法优化锅炉燃烧模型,ls-svm会搞,后面的智能算法不会
  • ¥20 MATLAB多目标优化问题求解
  • ¥15 windows2003服务器按你VPN教程设置后,本地win10如何连接?
  • ¥15 求一阶微分方程的幂级数