我有一张表格,列出了我们收到的订单。每个订单一行。
第二个表记录与订单相关的交易。
我正在尝试生成一份报告,该报告显示每行和每行的一个订单,以显示各种交易类型的总价值。
我的查询是:
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
但这很慢。我在适当的列上有索引。
我是否可以避免执行三个子查询,而只运行一个查询出成本、附加费和 Payments_received 的查询?