将具有不同条件和结果的两个查询设置到一个表中

时间:2015-01-07 09:43:18

标签: php mysql

如何编写mysql查询或使用不同结果集的两个不同查询可以转换为单个表的一个数组?

我有一张桌子t1:

date            company     product      sales
------------------------------------------------
2013-12-01      abc         a1           100
2014-12-01      abc         b1           50
2014-12-01      abc         c1           100
2014-12-01      xyz         x1           100

Query1 (based on selection of date='2014-12-01'):
--------------------------------------------------------

select company, sum(sales) as day_sales from t1 where date='2014-12-01' 
group by company;

will give:

company   day_sales
---------------------------
abc       150
xyz       100

Query2 (based on selection of date between '2014-12-01' and '2013-12-31'):
--------------------------------------------------------

select company, sum(sales) as previous_year_month_sale from t1 
where date between '2013-12-01' and '2013-12-31' group by company;

will give:

company   previous_year_month_sale
-----------------------------------
abc       100

如何将两个结果合并到一个表中,如:

company   day_sales   previous_year_mtd
-----------------------------------------
abc       150         100
xyz       100           0

请建议?

1 个答案:

答案 0 :(得分:0)

$sales = array();


在查询1结果循环中添加:

$sales $row['company'][0] = $row['day_sales'] ;


在查询2结果循环中添加:

$sales $row['company'][1] = $row['previous_year_month_sale'] ;


输出

foreach ($sales as $company => $val){
  echo "$company  $val[0]    $val[2] \n";
}