优化包含重复子查询的MySQL查询

时间:2017-08-13 15:29:30

标签: mysql sql join optimization subquery

我有以下查询现在正常工作,我一直在尝试优化它,因为我使用相同的子查询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

SQL小提琴:http://sqlfiddle.com/#!9/aecea/1

1 个答案:

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