Mysql查询:LEFT JOIN列出所有订单和"余额到期"对于客户,如果没有订单,只需列出客户。 3表

时间:2016-06-13 13:40:46

标签: mysql sql join left-join inner-join

我有一个客户表,订单表和付款表。

从这些开始,我试图为每条记录创建一个表:customer#,order#,Balance due。但是如果客户没有订单,那么我只想列出客户#,其他字段为NULL值。

使用LEFT JOIN我只能通过客户#和订单#来执行此操作,但我无法弄清楚如何在那里获得余额。我对Mysql相当新,并试图搜索答案,但无法。

这适用于客户#和订单#:

SELECT
    customers.cust_num,
    orders.order_id
FROM customers
LEFT JOIN orders ON customers.cust_num = orders.cust_num

但我正在尝试合并" orders.invoice_amount - SUM(payments.amount)AS balance_due"作为另一列,其中支付表通过名为" order_id"的字段与订单表相关联。在两者中。

也许是这样的: SELECT orders.invoice_amount - SUM(payments.amount) AS balance_due FROM payments, orders WHERE payments.order_id = orders.order_id

我知道如何做到这一点或指向正确的方向吗?

2 个答案:

答案 0 :(得分:1)

执行额外的LEFT JOIN,但是对按订单分组的付款进行子查询。所以,如果它在预先得到的结果中找到了记录,那么你就可以了。此外,我更改为使用表“别名”以提高可读性,特别是如果表名变长,或者您必须多次连接到查询中的同一个表。

SELECT
      c.cust_num,
      coalesce( o.order_id, 0 ) as Order_ID,
      coalesce( o.invoice_amount, 0 ) as InvoiceAmount,
      coalesce( Prepaid.TotalPaid, 0 ) as TotalPaid,
      coalesce( o.invoice_amount - coalesce( PrePaid.TotalPaid, 0 ), 0) as BalanceDue
   FROM 
      customers c
         LEFT JOIN orders o 
            ON c.cust_num = o.cust_num
            LEFT JOIN
            ( select 
                    p.order_id,
                    sum( p.amount ) as totalPaid
                 from
                    payments p
                 group by
                    p.order_id ) as PrePaid
               on o.order_id = PrePaid.order_id

答案 1 :(得分:1)

你可以试试像

这样的东西
SELECT
    customers.cust_num,
    orders.order_id, 
      orders.invoice_amount - SUM(payments.amount)
FROM customers
LEFT JOIN orders ON customers.cust_num = orders.cust_num
INNER JOIN payments P ON P..order_id = orders.order_id
group by cust_num,order_id,orders.invoice_amount