2017-08-13 8 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フィドル:あなたはinvoice_payments(invoice_payment_invoice_id, invoice_payment_amount)にインデックスをしたい、パフォーマンスを向上させるため

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; 

http://sqlfiddle.com/#!9/aecea/1

+0

MariaDB 10.2またはMySQL 8.0では、CTEを使用できます。 –

答えて

1

だけでサブクエリを使用しています。

+0

は予想通りに動作し、半分の時間で同じ結果が得られました。 [link](https://bucket.domekoto.com/?fvzwc.png)ゴードンに感謝します。私はwhere節に欠落した 'or'を追加しました。 – camilogr