简体   繁体   中英

Merging (or union) two result set with MySQL

I have two seperate MySQL queries which return two set of results that look like this

Query 1 result :

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

and:

Query 2 result :

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

All I need is to merge / union them so the final result will look like this:

Expected result

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

Please help, and if possible, with a bit of explaination. Thank you!

Use UNION ALL to merge the two queries results' sets into one result set, then use GROUP BY country with SUM to get the totals you are looking for, something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM