2017-09-07 18 views
1

私は2つのSQLクエリからデータを結合しています。これは、ループが多いので単一のSQLクエリとしてこれを行うより速い方法があるのだろうかと思います。その後、私は2つのアレイを作成PHP/SQL:クエリ結果を組み合わせる高速化

$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++; 
    } 
} 

をそして最後に、私は配列の組み合わせ:

を私は「OPTION_NAME」フィールドに別の文字列値を探して2つのクエリを持っています
//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++; 
       } 

      } 

     } 

    } 
} 

答えて

2

なぜ2つの異なるクエリで作業していますか? mysql IN( 'val'、 'val2');を使用します。

0
$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あなたのケースではあなたの助けあなたは、私はあなたが同じテーブルを結合したいと最初に表示さdidntのだろう。私は答えを削除して別の解決法を手助けしました

また、複数のレコードを避けるためにDISTINCTを使用してください。 SELECT DISTINCT USER_ID, OPTION VALUE FROM TABLE

関連する問題