【问题标题】:PHP MySQL how to retrieve records that match several different values in a single queryPHP MySQL如何在单个查询中检索匹配多个不同值的记录
【发布时间】:2014-08-15 09:49:57
【问题描述】:

我在 php 上有一个数组,其中包含我要检索的记录的一些 ID,我正在使用循环执行此操作,并多次执行查询以获取所有记录。

foreach ($receivers as $id) {

            $sth = $this->db->prepare("SELECT phone FROM contact WHERE idcontact = ?");

            $sth->execute(array($id));

            $res= $sth->fetch();
            echo $res['phone'] ;
            }

我怎样才能在一个查询中做到这一点,这样我就不会用数百个查询来打扰数据库?

【问题讨论】:

    标签: php mysql sql query-optimization


    【解决方案1】:
    $sth = $this->db->prepare("SELECT phone FROM contact WHERE idcontact IN (" . implode(",",$receivers) . ")");
    

    来源:http://www.w3resource.com/mysql/comparision-functions-and-operators/in-function.php

    更好的来源:http://dev.mysql.com/doc/refman/5.0/en/any-in-some-subqueries.html

    【讨论】:

      【解决方案2】:

      您可以将IN() 谓词与查询参数一起使用:

      $placeholders = implode(",", array_fill(1, count($receivers), "?"));
      
      $sth = $this->db->prepare("SELECT phone FROM contact WHERE idcontact IN ($placeholders)");
      
      $sth->execute($receivers);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多