避免多个子查询以提高查询速度

时间:2013-09-13 15:18:54

标签: mysql

我有一张表列出了我们收到的订单。每个订单一行。

第二个表记录与订单关联的交易。

我正在尝试生成一个报告,显示每行和每行一个订单,以显示各种类型交易的总价值。

我的查询是:

select 
orders.orderID, 
customers.username, 
(select sum(amount) from transactions where transactions.orderID=orders.orderID and transactionType IN (17) ) cost,
(select sum(amount) from transactions where transactions.orderID=orders.orderID and transactionType IN (18,19,20) ) surcharges,
(select sum(amount) from transactions where transactions.orderID=orders.orderID and transactionType IN (21,22) ) payments_received
from orders 
left join customers on orders.customerID=customers.customerID 
order by orderID

但这很慢。我在相应的列上有索引。

我是否可以避免执行三个子查询,而只是运行一个查询,以查看成本,附加费和payment_received?

1 个答案:

答案 0 :(得分:3)

这样的事情应该这样做:

SELECT orders.orderid
     , customers.username
     , Sum(CASE WHEN transactions.transactiontype IN (17        ) THEN transactions.amount END) As cost
     , Sum(CASE WHEN transactions.transactiontype IN (18, 19, 20) THEN transactions.amount END) As surcharges
     , Sum(CASE WHEN transactions.transactiontype IN (21, 22    ) THEN transactions.amount END) As payments_received
FROM   orders
 LEFT
  JOIN customers
    ON customers.customerid = orders.customerid
 LEFT
  JOIN transactions
    ON transactions.orderid = orders.orderid
GROUP
    BY orders.orderid
     , customers.username
ORDER
    BY orders.orderid