我试图将我的查询更新到MySQL,并发现我需要使用嵌套查询来获得我需要的结果。
我有以下代码: -
SELECT tbl_invoices.ID, tbl_invoices.customer_id, (SELECT Sum(tbl_invoices_payments.payment_amount) AS SumOfpayment_amount FROM tbl_invoices_payments WHERE invoice_id = id GROUP BY tbl_invoices_payments.invoice_id ) AS Payments
FROM tbl_invoices
WHERE (((tbl_invoices.customer_id)=11));
我收到错误: -
我需要的结果只是每张发票的所有付款的总和。
有人能指出我正确的方向吗?
答案 0 :(得分:1)
SELECT tbl_invoices.ID, tbl_invoices.customer_id, Sum(tbl_invoices_payments.payment_amount) AS SumOfpayment_amount
FROM tbl_invoices left outer join tbl_invoices_payments on tbl_invoices_payments.invoice_id = tbl_invoices.ID
GROUP BY tbl_invoices.ID
having tbl_invoices.customer_id=11;
答案 1 :(得分:-1)
我在Gouda的帮助下想出来了。
SELECT tbl_invoices.ID, tbl_invoices.customer_id, tbl_invoices.invoice_date, tbl_invoices.invoice_net, tbl_invoices.invoice_tax, tbl_invoices.invoice_gross, Sum(tbl_invoices_payments.payment_amount) AS SumOfpayment_amount
FROM tbl_invoices LEFT JOIN tbl_invoices_payments ON tbl_invoices.ID = tbl_invoices_payments.invoice_id
GROUP BY tbl_invoices.ID, tbl_invoices.customer_id, tbl_invoices.invoice_date, tbl_invoices.invoice_net, tbl_invoices.invoice_tax, tbl_invoices.invoice_gross
HAVING (((tbl_invoices.customer_id)=11));
谢谢。