MySQL计算选择不使用空子选择

时间:2013-03-11 15:55:52

标签: mysql sql select union

我试图通过一个SQL查询获得5个不同表中的结果总和。我有5个表,每个表可能包含一个属于该订单的记录。 5个表中所有记录的总和决定了总订单价格。

在此论坛上搜索,我提出了以下问题:

SELECT
  OrderTotal.total + Shipping.amount + Service.amount - Gift.amount - RMA.total as TotalCosts
FROM
  (SELECT SUM(price * amount) AS total FROM order WHERE order_id=123456) OrderTotal
  (SELECT amount FROM shipping WHERE order_id=123456) Shipping,
  (SELECT amount FROM service WHERE order_id=123456) Service,
  (SELECT SUM(price * amount) AS total FROM rma WHERE order_id=123456) RMA,
  (SELECT amount FROM gift WHERE order_id=123456) Gift

我现在面临的问题是,例如,当最后一个SELECT返回0行时,不会返回TotalCosts总数。

如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

如何使用UNION

SELECT  order_id, SUM(total) GrandTotal
FROM
        (
            SELECT  order_id, SUM(price * amount) AS total 
            FROM    `order` 
            WHERE   order_id = 123456
            UNION ALL
            SELECT  order_id, amount AS total 
            FROM    shipping 
            WHERE   order_id = 123456
            UNION ALL
            SELECT  order_id, amount AS total 
            FROM    service 
            WHERE order_id = 123456
            UNION ALL
            SELECT  order_id, SUM(price * amount) AS total 
            FROM    rma 
            WHERE   order_id = 123456
            UNION ALL
            SELECT  order_id, amount AS total 
            FROM    gift 
            WHERE   order_id=123456
        ) subTable
GROUP   BY order_id

答案 1 :(得分:0)

您可以使用 IFNULL 函数来解决

SELECT
  IFNULL(OrderTotal.total,0) + IFNULL(Shipping.amount + IFNULL(Service.amount - IFNULL(Gift.amount,0) - RMA.total as TotalCosts
FROM
  (SELECT SUM(price * amount) AS total FROM order WHERE order_id=123456) OrderTotal
  (SELECT amount FROM shipping WHERE order_id=123456) Shipping,
  (SELECT amount FROM service WHERE order_id=123456) Service,
  (SELECT SUM(price * amount) AS total FROM rma WHERE order_id=123456) RMA,
  (SELECT amount FROM gift WHERE order_id=123456) Gift