Mysql 查询:LEFT JOIN 列出所有订单和 "balance due" 一个客户,如果没有订单,只列出客户。 3张桌子

Mysql Query: LEFT JOIN List all orders and "balance due" for a customer, if no orders, just list customer. 3 Tables

我有客户 table、订单 table 和付款 table。

我试图从这些中得到一个 table 每条记录都有:客户#、订单#、到期余额。但是,如果客户没有订单,那么我只想列出其他字段为 NULL 值的客户#。

使用 LEFT JOIN 我可以只用 customer# 和 order# 做到这一点,但我也无法弄清楚如何获得余额。我是 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" 合并为另一列,其中付款 table 与订单 table 通过一个名为 "order_id" 的字段相关联。

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

知道我该怎么做吗?或者指出正确的方向?

做一个额外的 LEFT JOIN,但对按订单分组的付款进行子查询。因此,如果它在预查询结果中找到了一条记录,那么您就可以开始了。此外,为了更短的可读性,我改为使用 table "aliases",特别是如果 table 名称变长,或者您必须在查询中多次连接到同一个 table。

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

你可以试试

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