【问题标题】:PHP/SQL: Faster Way to Combine Query ResultsPHP/SQL:更快的组合查询结果的方法
【发布时间】:2017-09-07 21:01:34
【问题描述】:

我正在连接来自两个 SQL 查询的数据,我想知道是否有一种更快的方法可以将其作为单个 SQL 查询来执行,因为这涉及到很多循环。我有两个查询在“option_name”字段中查找不同的字符串值:

 $sql01= "SELECT user_id, option_value FROM wp_wlm_user_options WHERE option_name = 'wpm_login_date' ORDER BY user_id";

 $sql02 = "SELECT user_id, option_value FROM wp_wlm_user_options WHERE option_name ='stripe_cust_id' ORDER BY user_id ";

然后我创建两个数组:

//Process the 1st SQL query data into an Array

$result_array01 = array();
$j = 0;

while($r = mysql_fetch_assoc($result01)) {

    if(!empty($r['option_value'])){

            //User Id and Last Login

            $result_array01[$j]['user_id'] = $r['user_id'];
            $result_array01[$j]['last_login'] = $r['option_value'];
            $j++;
    }
}

//Process the 2nd SQL query data into an Array

$result_array02 = array();
$k = 0;

while($s = mysql_fetch_assoc($result02)) {

    if(!empty($s['option_value'])){

            //User Id and Stripe Customer Id

            $result_array02[$k]['user_id'] = $s['user_id'];
            $result_array02[$k]['cust_id'] = $s['option_value'];
            $k++;
    }   
}

最后,我合并了数组:

//Combine the SQL query data in single Array

$combined_array = array();
$l = 0;

foreach($result_array01 as $arr01){

    //  Check type
    if (is_array($arr01)) {

         //mgc_account_print("hello: " . $arr01['user_id'] . "\r\n");

         foreach($result_array02 as $arr02){

            //  Check type
            if (is_array($arr02)) {         


                //Check if User Id matches
                if($arr01['user_id'] == $arr02['user_id']){

                    //Create Array with User Id, Cust Id and Last Login

                    $combined_array[$l]['user_id'] =  $arr01['user_id'];
                    $combined_array[$l]['last_login'] =  $arr01['last_login'];
                    $combined_array[$l]['cust_id'] =  $arr02['cust_id'];
                    $l++;
                }

            } 

         }

    }   
}

【问题讨论】:

    标签: php sql arrays


    【解决方案1】:

    为什么你在两个不同的查询中做? 使用mysql IN('val', 'val2');

    【讨论】:

      【解决方案2】:
      $sql01= "SELECT tbl1.user_id, tbl1.option_value FROM wp_wlm_user_options as tbl1 WHERE tbl1.option_name = 'wpm_login_date' 
      union all 
      SELECT tbl2.user_id, tbl2.option_value FROM wp_wlm_user_options as tbl2. WHERE tbl2.option_name ='stripe_cust_id' ";
      

      但是在你的情况下使用 OR/AND 会对你有所帮助,我一开始并没有看到你想要组合同一张桌子。我没有删除我的答案来帮助您寻求另一个解决方案

      您还应该使用 DISTINCT 来避免多条记录。 SELECT DISTINCT USER_ID, OPTION VALUE FROM TABLE

      【讨论】:

        猜你喜欢
        • 2021-07-02
        • 1970-01-01
        • 2017-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-14
        • 2010-11-20
        相关资源
        最近更新 更多