我有以下查询现在正常工作,我一直在尝试优化它,因为我使用相同的子查询4次。能够提出更好/更智能的解决方案将会很棒。谢谢
以下是查询:
select invoices.invoice_id ,invoices.invoice_amount ,( select SUM(invoice_payment_amount) as total FROM invoice_payments where invoice_payment_invoice_id = invoices.invoice_id ) as payments ,round((invoices.invoice_amount-( select SUM(invoice_payment_amount) as total FROM invoice_payments where invoice_payment_invoice_id = invoices.invoice_id )),2) as balance from invoices where ( round((invoices.invoice_amount - (select SUM(invoice_payment_amount) as total FROM invoice_payments where invoice_payment_invoice_id = invoices.invoice_id) ),2) ) > 0 or ( round((invoices.invoice_amount - (select SUM(invoice_payment_amount) as total FROM invoice_payments where invoice_payment_invoice_id = invoices.invoice_id) ),2) ) IS NULL order by balance
答案 0 :(得分:1)
只需使用子查询:
select i.invoice_id, i.invoice_amount, i.payments,
round((i.invoice_amount- i.payments), 2) as balance
from (select i.*,
(select sum(ip.invoice_payment_amount)
from invoice_payments ip
where ip.invoice_payment_invoice_id = i.invoice_id
) as payments
from invoices i
) i
where round((i.invoice_amount- i.payments), 2) > 0 or
round((i.invoice_amount- i.payments), 2) is null
order by balance;
为了获得更好的性能,您需要invoice_payments(invoice_payment_invoice_id, invoice_payment_amount)
上的索引。