将6个查询合并为1个结果集以进行导出?

时间:2013-08-13 19:45:54

标签: php mysql csv

好的,所以这可能听起来有点奇怪,可能过于复杂。情况就是这样。我2组3个查询。我将尝试用一个简单的例子来解释我想要做的事情:

查询:

//First set of queries
$query1 = "SELECT Name, Date FROM Table1";
$query2 = "SELECT Type, Place, Location FROM Table2";
$query3 = "SELECT One FROM Table3";

//Second set of queries
$query4 = "SELECT Name, Date FROM Table1 WHERE ID=1";
$query5 = "SELECT Type, Place, Location FROM Table2 WHERE ID=1";
$query6 = "SELECT One FROM Table3 WHERE ID=1";

当我告诉你我不能将这两组查询结合起来时,你只需要相信我。这些都是简化的select语句,以获得我想要做的概念。

所以这是我的PHP代码:

//Set 1
$data1 = mysql_query($query1) or die(mysql_error());
$data2 = mysql_query($query2) or die(mysql_error());
$data3 = mysql_query($query3) or die(mysql_error());
while ($line1 = mysql_fetch_array($data1, MYSQL_ASSOC) &&
        $line2 = mysql_fetch_array($data2, MYSQL_ASSOC)) {
    while ($line3 = mysql_fetch_array($data3, MYSQL_ASSOC)) {
        //COMBINE $line1, line2, line3 into a single $lineSet1 -- HOW DO I DO THIS?
    }
}

//Set 2
$data4 = mysql_query($query4) or die(mysql_error());
$data5 = mysql_query($query5) or die(mysql_error());
$data6 = mysql_query($query6) or die(mysql_error());
while ($line4 = mysql_fetch_array($data4, MYSQL_ASSOC) &&
        $line5 = mysql_fetch_array($data5, MYSQL_ASSOC)) {
    while ($line6 = mysql_fetch_array($data6, MYSQL_ASSOC)) {
        //COMBINE $line4, line5, line6 into a single $lineSet2 -- HOW DO I DO THIS?
    }
}

//Append $lineset1 and $lineset2 so I have 1 resultset $results
$result = array_merge($lineSet1, $lineSet2);
//So now I can pass this $result array into my array2csv function that takes a multidimensional array:
function array2csv(array &$array)
{
   if (count($array) == 0) {
     return null;
   }
   ob_start();
   $df = fopen("exportedLeads{$_SESSION['id']}.csv", 'w');
   fputcsv($df, array_keys(reset($array)));
   foreach ($array as $row) {
      fputcsv($df, $row);
   }
   fclose($df);
   return ob_get_clean();
}

我知道这看起来真的很复杂,但我很困惑,而且不是那么擅长php。任何帮助,将不胜感激。谢谢!

TABLE1:

ID | Name | Date

TABLE2:

ID | Table1_ID | Type | Place | Location

TABLE3:

ID | Table1_ID | One
编辑:我一直在阅读JOIN陈述。这可能是一个案例吗?

2 个答案:

答案 0 :(得分:1)

您可以将两个集合恢复为单个查询,例如使用JOIN假设您的ID匹配。

首先设置为1个查询:

SELECT t1.Name, t1.Date, t2.Type, t2.Place, t3.One FROM Table1 t1
  JOIN Table2 t2
    ON t2.Table1_ID = t1.ID
  JOIN Table3 t3
    ON t3.Table1_ID = t1.ID

第二次设置为1个查询:

SELECT t1.Name, t1.Date, t2.Type, t2.Place, T2.Location, t3.One
  FROM Table1 t1
  JOIN Table2 t2
    ON t2.Table1_ID = t1.ID
  JOIN Table3 t3
    ON t3.Table1_ID = t1.ID
 WHERE t1.ID = 1

答案 1 :(得分:0)

假设您的三个查询都返回了相同的行数,您可以滥用赋值运算符:

while(($row1 = mysql_fetch($result1))
   && ($row2 = mysql_fetch($result2))
   && ($row3 = mysql_fetch($result3))) {

并行地从所有三个结果集中获取。缺点是,如果结果集的长度不同,则只能获取与SHORTEST结果集中一样多的记录。例如只要这些fetch调用中的任何一个返回false,整个while就会中止,即使其他两个结果中仍有数据。