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.

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

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料