如果存在行,MySQL查询仅返回值

时间:2014-09-17 12:41:28

标签: mysql sum left-join

我有以下查询,它可以完美地运行,但前提是每个选择都找到一行。

如果没有找到行但我还没有得到正确的回报,我试图添加IFNULL返回0。

SELECT IFNULL(paid_value,0)-IFNULL(ordered_value,0)+IFNULL(credit_value,0) AS account_balance
            FROM
            (
              SELECT customer_id, SUM(order_total) AS ordered_value
              FROM orders
              WHERE customer_id = '1'
              GROUP BY customer_id
            ) AS orders
            LEFT JOIN
            (
              SELECT customer_id, SUM(amount) AS paid_value
              FROM transactions
              WHERE customer_id = '1'
              GROUP BY customer_id
            ) as payments
            ON orders.customer_id = payments.customer_id
            LEFT JOIN
            (
                SELECT customer_id, SUM(amount) AS credit_value
                FROM credits
                WHERE customer_id = '1'
                GROUP BY customer_id
            ) as credits
            ON orders.customer_id = credits.customer_id

此查询当前返回空,它不返回NULL或0。

当我跑步时

              SELECT customer_id, SUM(order_total) AS ordered_value
              FROM orders
              WHERE customer_id = '1'
              GROUP BY customer_id

它也会返回空,而不是NULL或0,除非有一行。为了使完整查询起作用,3个单独的查询中的每一个都需要在其中包含一行。

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

如果因为没有列有结果集,所以返回一个空的结果集,如果你想在任何情况下总是显示一行,你可以尝试一些这样的技巧,例如:

SELECT IFNULL(SUM(payments.paid_value),0)-IFNULL(SUM(orders .ordered_value),0)+IFNULL(SUM(credits.credit_value),0) AS account_balance
FROM 
(SELECT 1 AS idx, 0 AS paid_value, 0 AS ordered_value, 0 AS credit_value) a
LEFT JOIN
            (
              SELECT 1 AS idx, customer_id, SUM(order_total) AS ordered_value
              FROM orders
              WHERE customer_id = '1'
              GROUP BY customer_id
            ) AS orders
            ON a.idx = orders.idx 
            LEFT JOIN
            (
              SELECT customer_id, SUM(amount) AS paid_value
              FROM transactions
              WHERE customer_id = '1'
              GROUP BY customer_id
            ) as payments
            ON orders.customer_id = payments.customer_id
            LEFT JOIN
            (
                SELECT customer_id, SUM(amount) AS credit_value
                FROM credits
                WHERE customer_id = '1'
                GROUP BY customer_id
            ) as credits
            ON orders.customer_id = credits.customer_id
            GROUP BY a.idx

该示例是一个概念证明,即使在基础表中没有元素的情况下,甚至在需要始终返回具有默认值的行的其他情况下也可以进行调整。

答案 1 :(得分:0)

如果你想要行事件,如果没有可用的数据,那么我想你应该有UNION。或者在这种情况下,您可以包括Customer Table&将每个表放在右侧,制作LEFT JOIN

我认为以下选择会给你一个IDEA。

SELECT O.customer_id, SUM(O.order_total) AS ordered_value
              FROM Customers C
              left join orders O on C.ID =o.customer_id
              WHERE O.customer_id = '1'
              GROUP BY O.customer_id