Mysql与left join和group by连接

时间:2015-02-26 05:16:23

标签: mysql left-join inner-join

我想结合三个sql查询,下面给出查询,站点和商品列是常用列,我想在我的结果中有9列,如果你逐个运行这三个查询,你将得到3个结果,有3列,我想结合这三个结果

select distinct
  a.site,a.goods,
  sum(a.quantity)
from
  stock_consumed a
group by
  a.site,a.goods


select distinct
  b.site,
  b.goods,sum(b.quantity)
from
  opening_balance b
group by
  b.site,b.goods


select distinct
  c.site,
  c.goods,sum(c.no_of_units)
from
  inward_stock c
group by
  c.site,c.goods

1 个答案:

答案 0 :(得分:0)

您正在寻找union。它允许您组合两个查询的结果,只要它们的结果具有相同的列数。

select distinct a.site,a.goods,sum(a.quantity) from stock_consumed a group by a.site,a.goods
union 
select distinct b.site,b.goods,sum(b.quantity) from opening_balance b group by b.site,b.goods
union
select distinct c.site,c.goods,sum(c.no_of_units) from inward_stock c group by c.site,c.goods