PHP / SQL:更快地结合查询结果

时间:2017-09-07 21:01:35

标签: php sql arrays

我正在加入来自两个SQL查询的数据,并且我想知道是否有更快的方法将其作为单个SQL查询执行,因为涉及大量循环。我有两个查询在" option_name"中寻找不同的字符串值。字段:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
    <TargetFrameworks>netcoreapp2.0;net451;</TargetFrameworks>
    <RootNamespace>Apples</RootNamespace>
    <SignAssembly>true</SignAssembly>
    <DelaySign>false</DelaySign>
    <AssemblyOriginatorKeyFile>..\..\GeneratedKey.snk</AssemblyOriginatorKeyFile>
  </PropertyGroup>

  <ItemGroup>
    <None Remove="packages.config" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="CommandLineParser" Version="2.1.1-beta" />
    <PackageReference Include="Newtonsoft.Json" Version="10.0.3" />
    <PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
    <PackageReference Include="System.Composition" Version="1.1.0" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\Oranges\Oranges.csproj" />
  </ItemGroup>
</Project>

然后我创建了两个数组:

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

2 个答案:

答案 0 :(得分:2)

为什么你要做两个不同的查询? 使用mysql IN(&#39; val&#39;,&#39; val2&#39;);

答案 1 :(得分: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