mySQL 2 个不同表格中两个值的总和

mySQL sum of two values in 2 different tables

我有 2 个相同的表,每个表中都有相同的列 - "quantity" 和 "reference"。这些列中的值设置如下:

table_1
reference    quantity
TS00001      235
TS00002      400
TS00003      850
...

table_2
reference    quantity
TS00001      670
TS00002      210
TS00003      150
...

我需要连接表格并输出每个匹配参考 ID 的数量字段的总和,例如:

reference    total_quantity
TS00001      905
TS00002      610
TS00003      1000
...

我一直在尝试 LEFT JOIN 和其他方法,但我很快就无处可去,所以如果有人能抽出时间引导我走上正确的轨道,我将不胜感激。谢谢

您需要UNION两个表:

SELECT reference, SUM(quantity) AS total_quantity
FROM (
  SELECT reference, quantity
  FROM table_1

  UNION ALL

  SELECT reference, quantity
  FROM table_2) AS t
GROUP BY reference

这样您就可以保证获得 reference 值的记录,即使它只包含在两个表中的一个中。

您可以使用 union all 运算符将两列视为一个列:

SELECT   reference, SUM(quantity)
FROM     (SELECT reference, quantity FROM table_1
          UNION ALL
          SELECT reference, quantity FROM table_2) t
GROUP BY reference