2017-09-07 32 views
1

我正在加入來自兩個SQL查詢的數據,我想知道是否有更快的方式將其作爲單個SQL查詢執行,因爲涉及大量循環。我有一個尋找不同的字符串值,在「OPTION_NAME」字段的兩個查詢: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++; 
    } 
} 

最後,我結合陣列:

//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

爲什麼你在兩個不同的查詢? 使用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會幫助你在你的情況下,我一開始並沒有看到你想要組合同一張表。我沒有刪除我的答案,以幫助您獲得另一個解決方案

另外,您應該使用DISTINCT來避免多條記錄。 SELECT DISTINCT USER_ID, OPTION VALUE FROM TABLE