将两个结果集与MySQL合并(或联合)

时间:2014-12-02 13:50:28

标签: mysql merge sum union

我有两个单独的MySQL查询,返回两组看起来像这样的结果

查询1结果

country  | buyers | payment |  num_of_sales
UK       |   5    | 106.45  |    4
Thailand |   6    | 250.10  |    3

查询2结果

country | buyers | payment |  num_of_sales
UK      |   2    | 150.00  |    1
Norway  |   9    | 310.80  |    2

我需要的是合并/合并它们,以便最终结果如下:

预期结果

 country | buyers | payment |  num_of_sales
 UK      |   7    | 256.45  |    5
Thailand |   6    | 250.10  |    3
 Norway  |   9    | 310.80  |    2

请帮助,如果可能的话,请加以解释。谢谢!

1 个答案:

答案 0 :(得分:2)

使用UNION ALL合并两个查询结果'设置为一个结果集,然后使用GROUP BY countrySUM来获取您要查找的总数,如下所示:

SELECT
  country, 
  SUM(buyers) AS buyers, 
  SUM(payment) AS payment, 
  SUM(num_of_sales) AS num_of_sales
FROM
(  
   SELECT country, buyers, payment, num_of_sales
   FROM -- your query1 results
   UNION ALL
   SELECT country, buyers, payment, num_of_sales
   FROM -- your  query2 result2  
) AS t
GROUP BY country