我有以下正在完美工作的查詢,我一直在嘗試優化它,因爲我使用相同的子查詢4次。提出一個更好/更智能的解決方案將是非常好的。謝謝優化MySQL查詢,其中包括重複的子查詢
下面是該查詢:
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
SQL小提琴:http://sqlfiddle.com/#!9/aecea/1
在MariaDB 10.2或MySQL 8.0中,您可以使用CTE。 –