Forum Moderators: open
table 1
-------
apples 5
bananas 2
oranges 3
table 2
-------
apples 3
bananas 1
oranges 0
output
------
apples 8
bananas 3
oranges 3
Thanks :)
Tom
The tricky part of this is when you don't have fruits listed in one of the tables. If you know that all the fruits are listed in table1, but might not be in table2, you could use this query:
SELECT table1.name, (ifnull(table1.cnt,0) + ifnull(table2.cnt,0)) as cnt
FROM table1 left join table2 on table1.name = table2.name
GROUP BY table1.name
Otherwise, the following query should get you what you want:
SELECT table1.name, (ifnull(table1.cnt,0) + ifnull(table2.cnt,0)) as cnt
FROM table1 left join table2 on table1.name = table2.name
GROUP BY table1.name
union
SELECT table2.name, (ifnull(table1.cnt,0) + ifnull(table2.cnt,0)) as cnt
FROM table1 right join table2 on table1.name = table2.name
GROUP BY table2.name
This assumes you're using MySQL - I'm not sure what databases support the ifnull syntax, if you find that yours does not, let me know what it is and I'll try to figure out what you need.
Chad
UNION ALLin this case.
The default behavior for
UNIONis that duplicate rows are removed from the result. A
DISTINCTkeyword has no effect other than the default because it also specifies duplicate-row removal. With the
ALLkeyword, duplicate-row removal does not occur and the result includes all matching rows from all the
SELECTstatements. This becomes very very important when adding values because if two fruits existed in both tables with the same exact quantity, one of the rows would be removed from the result set as it would be recognized as a duplicate. And now the total would return only half of what it is supposed to return.
SELECT
fruit,
SUM(qty) AS total
FROM
(SELECT fruit, qty FROM fruit1)
UNION ALL
(SELECT fruit, qty FROM fruit2)
AS fruitAll
GROUP BY fruit
;