MySQL SUM()的两列来自连接两个表

时间:2015-12-29 03:27:37

标签: mysql

我需要连接两个表,并在每个表中获得一列的SUM()。

    mysql> select * from day_sales2;
    +--------+------------+
    | id     | ds_oversht |
    +--------+------------+
    | 119263 |      -0.17 |
    | 119336 |       0.55 |
    | 119409 |       3.08 |
    | 119482 |     -33.25 |
    | 119555 |       1.27 |
    | 119628 |       0.32 |
    | 119701 |      -0.15 |
    | 119774 |       6.57 |
    | 119847 |      -0.06 |
    | 119920 |     -12.04 |
    | 119993 |     -12.40 |
    | 120066 |     -38.90 |
    | 120139 |      20.56 |
    | 120212 |     -17.11 |
    | 120285 |      -0.51 |
    | 120358 |       0.04 |
    | 120431 |       3.23 |
    | 120504 |      -0.89 |
    | 120577 |       2.13 |
    | 120650 |       0.57 |
    | 120723 |      -1.15 |
    | 120796 |       1.99 |
    | 120869 |       9.29 |
    | 120942 |       6.95 |
    | 121015 |       3.22 |
    | 121088 |      -0.59 |
    | 121161 |      -0.89 |
    | 121234 |      -1.00 |
    +--------+------------+

    mysql> select * from over_short_adj2;
    +-------+---------+-----------+
    | id    | main_id | cd_amount |
    +-------+---------+-----------+
    | 45881 |  119920 |      0.66 |
    | 45882 |  119920 |      1.19 |
    | 45907 |  119920 |      4.81 |
    | 46017 |  120212 |      3.35 |
    | 46018 |  120066 |     16.85 |
    +-------+---------+-----------+

我使用此查询来完成这项工作:

    SELECT SUM(t1.ds_oversht) sum1, SUM(t2.cd_amount) sum2
    FROM day_sales2 t1 
    LEFT JOIN over_short_adj2 t2 ON t1.id = t2.main_id

但sum1不正确,因为join是一对多的。我怎么能让这个查询工作?

3 个答案:

答案 0 :(得分:1)

在执行SUM之前,您应首先获得day_sales2的{​​{1}}:

LEFT JOIN

编辑:

如果您只想要一行,我认为不需要SELECT t1.id, t1.sum1, SUM(t2.cd_amount) AS sum2 FROM ( SELECT id, SUM(ds_oversht) AS sum1 FROM day_sales2 GROUP BY id ) t1 LEFT JOIN over_short_adj2 t2 ON t1.id = t2.main_id GROUP BY t1.id, t1.sum1

JOIN

答案 1 :(得分:1)

如果您只想从两个表中获取一行总和,则可以使用UNION

SELECT SUM(ds_oversht) from day_sales2
UNION
SELECT SUM(cd_amount) from over_short_adj2;

答案 2 :(得分:0)

    SELECT SUM(sum1) sum1, SUM(sum2) sum2 FROM (
    SELECT
        t1.id,
        t1.sum1, 
        SUM(t2.cd_amount) sum2
    FROM (
        SELECT id, SUM(ds_oversht) sum1
        FROM day_sales2
        GROUP BY id
    ) t1
    LEFT JOIN over_short_adj2 t2 
        ON t1.id = t2.main_id
    GROUP BY t1.id, t1.sum1
    ) t3

这样做,感谢Felix的答案。