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

时间:2011-09-15 14:06:29

标签: mysql sum

在MySQL中我有两个表:

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

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

我需要将表Qty(等式7)和表MC(等式3)中的Amex列相加,并将结果作为总数量。

当我这样做时

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

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

4 个答案:

答案 0 :(得分:14)

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

答案 1 :(得分:2)

如果您希望避免使用Union或Union ALL(可能出于效率原因),则以下方法有效:

SELECT (1.Qty+2.Qty) AS total_qty FROM (SELECT SUM(Qty) Qty FROM MC) 1,
(SELECT SUM(Qty) Qty FROM Amex) 2; 

以下是一个示例,如果您希望将其展开以包含Group By条件。假设我们在MC和Amex上都有Cust_ID来识别每个订单的客户,我们想知道每个客户的总和。代码将如下所示:

SELECT COALESCE(1.Cust_ID, 2.Cust_ID) Cust_ID, (1.Qty+2.Qty) AS total_qty 
FROM (SELECT Cust_ID, SUM(Qty) Qty FROM MC GROUP BY Cust_ID) 1 
FULL OUTER JOIN (SELECT Cust_ID, SUM(Qty) Qty FROM Amex GROUP BY Cust_ID) 2 ON 1.Cust_ID = 2.Cust_ID; 

如果数据库中存在Customer表,则可以将其简化为:

SELECT c.Cust_ID, (1.Qty+2.Qty) AS total_qty FROM Customer c 
LEFT JOIN (SELECT Cust_ID, SUM(Qty) Qty FROM MC GROUP BY Cust_ID) 1 ON 1.Cust_ID = c.Cust_ID
LEFT JOIN (SELECT Cust_ID, SUM(Qty) Qty FROM Amex GROUP BY Cust_ID) 2 ON 2.Cust_ID = c.Cust_ID;

答案 2 :(得分:0)

SELECT SUM(Qty) AS total_qty FROM (SELECT Qty FROM amex UNION SELECT Qty FROM mc);

答案 3 :(得分:0)

那又如何:

SELECT (SELECT SUM(`Qty`) FROM `MC`) + (SELECT SUM(`Qty`) FROM `Amex`) AS `sumf`;