如何对 MySQL 中多个表的列求和?

2022-01-09 00:00:00 sum mysql

在 MySQL 中,我有两个表:

In MySQL I have two tables:

Table MC:
----------------
|TransNo | Qty |
|--------|-----|
|  xxx1  |  4  | 
|  xxx3  |  3  |

Table Amex:
----------------
|TransNo  | Qty |
|---------|-----|
|  xxx1   |  2  |
|  xxx5   |  1  | 

我需要对表 MC (eq. 7) 和表 Amex (eq. 3) 中的 Qty 列求和并得到结果作为总数量.

I need to sum the Qty column from table MC (eq. 7) and table Amex (eq. 3) and have result as Total Qty.

当我这样做时

SELECT (SUM(amex.Qty) + SUM(mc.Qty)) as total_qty from amex, mc

我得到了笛卡尔积 (20),但我需要的正确答案是 10.我需要如何更改此查询以获得正确的结果?

I get the cartesian product (20), but the correct answer I need is 10. How do I need to change this query to get the correct result?

推荐答案

SELECT SUM(t.Qty) AS total_qty
    FROM (SELECT Qty FROM MC
          UNION ALL
          SELECT Qty FROM Amex) t

相关文章