循环查看2个查询的结果

时间:2012-02-07 22:32:02

标签: php mysql

我有2个查询显示月份到目前为止的总计。我需要循环遍历它们,以便它们最终位于同一个表中。是否可以组合WHILE或组合查询以使ORDERS交替?

$MTDcurrent = $db->Execute("SELECT SUM(order_total) AS MTDC, month(date_purchased) AS Months FROM " . TABLE_ORDERS ." 
                        WHERE orders_status IN(1,2,3,100,101,103,105) AND date(date_purchased) BETWEEN DATE_FORMAT(current_date,'%Y-01-01') AND current_date GROUP BY Months ASC LIMIT 10 ");

$MTDprevious = $db->Execute("SELECT SUM(order_total) AS MTDP, month(date_purchased) AS Months FROM " . TABLE_ORDERS ." 
                        WHERE orders_status IN(1,2,3,100,101,103,105) AND date(date_purchased) BETWEEN DATE_FORMAT(date_sub(current_date, INTERVAL 1 year),'%Y-01-01') AND date_sub(current_date, INTERVAL 1 year)
                        GROUP BY Months ASC LIMIT 10 ");

先谢谢

2 个答案:

答案 0 :(得分:0)

您可以使用while循环直接执行此操作:

while( ($row = array_shift( $MTDcurrent)) || ($row = array_shift( $MTDprevious))){
    $row = 'your data';
}

但是,我不认为这种清洁明显的方式。您可能宁愿使用array_merge合并数组(如果没有大量数据):

foreach( array_merge( $MTDcurrent, $MTDprevious) as $row){
   $row = 'your data';
}

如果您的代码对性能至关重要且会使用大量数据,则应使用next函数实现Iterator,如下所示:

public function next() {
  $this->row = mysql_fetch_assoc( $this->query);
  if( $this->row){
     return;
  }

  if( count( $this->queries)){
    $this->query = mysql_query( array_shift( $this->queries));
    $this->next();
  }
}

警告:这只是一个想法,而不是你应该依赖的整个实现!

编辑等等,我提出错误的问题,你正在寻找mysql UNION statement

答案 1 :(得分:0)

这是一种避免多次查询的略有不同的方法。我没有尝试过,因为我现在使用的机器上没有RDBMS,但它应该足够接近 -

SELECT
    SUM(order_total) AS MTDP,
    month(date_purchased) AS Months,
    year(date_purchased) AS Years
FROM orders
WHERE orders_status IN(1,2,3,100,101,103,105)
AND DATE(date_purchased) > DATE_FORMAT(DATE_SUB(CURRENT_DATE, INTERVAL 1 year),'%Y-01-01')
GROUP BY Years, Months
ORDER BY Months ASC, Years ASC

在您对评论的回复中 - 您可以将WHERE子句的日期部分修改为两个WHERE子句的组合

AND (
        (date(date_purchased) BETWEEN DATE_FORMAT(current_date,'%Y-01-01') AND current_date)
    OR
        (date(date_purchased) BETWEEN DATE_FORMAT(date_sub(current_date, INTERVAL 1 year),'%Y-01-01') AND date_sub(current_date, INTERVAL 1 year))
)