MySql:如何从不同的表中获取SUM值?

时间:2011-12-03 07:06:18

标签: mysql sum

对于我想要的每个订单,获取产品总数和付款总额以获得余额。

这是表格的简化版本:

ORDERS
--------------------
|ord_id|customer_id|
--------------------
|     1|        XYZ|
|     .|          .|
|     .|          .|
|     .|          .|
--------------------

ORDER_DETAILS
-----------------------------------------
|det_id|ord_id|product_id|quantity|price|
-----------------------------------------
|     1|     1|    AAA001|       3|   30|
|     2|     1|    BBB002|       2|    5|
|     .|     .|         .|       .|    .|
|     .|     .|         .|       .|    .|
|     .|     .|         .|       .|    .|
-----------------------------------------

PAYMENTS
----------------------
|pay_id|ord_id|amount|
----------------------
|     1|     1|    10|
|     2|     1|    20|
|     3|     1|    10|
|     .|     .|     .|
|     .|     .|     .|
|     .|     .|     .|
----------------------

此查询不会返回正确的付款值,只有在产品数量与付款次数相同时才能获得正确的付款值:

SELECT o.ord_id, SUM(quantity * price) AS total_order, SUM(amount) AS total_payments
FROM orders AS o 
INNER JOIN order_details AS d ON o.ord_id = d.ord_id
INNER JOIN payments AS p ON o.ord_id = p.ord_id
GROUP BY o.ord_id

这是预期的结果:

-----------------------------------
|ord_id|total_order|total_payments|
-----------------------------------
|     1|        100|            40|
|     .|          .|             .|
|     .|          .|             .|
|     .|          .|             .|
-----------------------------------

提前致谢。

2 个答案:

答案 0 :(得分:6)

分别执行两个查询,然后加入结果。对我来说,逻辑上更有意义:

SELECT
    ot.ord_id, 
    ot.order_total,
    op.order_paid
FROM
    (
        SELECT
            ord_id,
            SUM(price * quantity) AS order_total
        FROM
            ORDER_DETAILS
        GROUP BY
            ord_id
    ) AS ot
    INNER JOIN (
        SELECT
            ord_id,
            SUM(amount) AS order_paid
        FROM
            PAYMENTS
        GROUP BY
            ord_id
    ) AS op ON (op.ord_id = ot.ord_id)
;

...

 ord_id | order_total | order_paid 
--------+-------------+------------
      1 |         100 |         40
(1 row)

答案 1 :(得分:0)

尝试按det_idWITH ROLLUP子句进行分组:

SELECT o.ord_id, SUM(quantity * price) AS total_order, SUM(amount) AS total_payments
FROM orders AS o 
INNER JOIN order_details AS d ON o.ord_id = d.ord_id
INNER JOIN payments AS p ON o.ord_id = p.ord_id
GROUP BY o.ord_id, o.det_id WITH ROLLUP