MySQL合并两张表求和

MySQL merge two tables and get sum

我有一个 tableA:

+------+--------+-------+
| name | code   | num   |
+------+--------+-------+
| A    | no1    | 300   |
| A    | no2    | 100   |
+------+--------+-------+

我还有一个tableB:

+------+--------+-------+
| name | code   | num   |
+------+--------+-------+
| A    | no1    | -100  |
| A    | no5    | 77    |
| B    | no7    | 2     |
+------+--------+-------+

我的目标是想要tableC这样:

+------+--------+-------+
| name | code   | num   |
+------+--------+-------+
| A    | no1    | 200   |
| A    | no2    | 100   |
| A    | no5    | 77    |
| B    | no7    | 2     |
+------+--------+-------+

我用了union和join,但是结果不对,请告诉我如何得到TableC

因此,您需要的不是 JOIN,而是 UNION。您可以使用“UNION ALL”或“UNION”,这取决于您是否想要重复的行。

无论如何,在 UNION 之后,将结果分组到子查询中以获得 SUM()

SELECT
u.name,
u.code,
SUM(u.num),
FROM
(
SELECT name, code, num FROM tableA
UNION ALL
SELECT name, code, num FROM tableB
) u
GROUP BY u.name, u.code