2017-08-13 82 views
1

我有以下正在完美工作的查詢,我一直在嘗試優化它,因爲我使用相同的子查詢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

+0

在MariaDB 10.2或MySQL 8.0中,您可以使用CTE。 –

回答

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)的索引。

+0

按預期工作,在一半時間內結果相同。 [鏈接](https://bucket.domekoto.com/?fvzwc.png)謝謝戈登。我只是在where子句中添加了一個缺少的'or'。 – camilogr