我写了一个查询,显示退款总额和总发票金额,该方法已用于特定订单的退款或发票(现金,信用卡或结账)。
我的查询如下:
SELECT Method, SUM(total_invoiced), SUM(total_refunded)
FROM
(SELECT refunds.method_rf AS Method, 0 AS total_invoiced,
SUM(refunds.ref_value) AS total_refunded
FROM refunds LEFT JOIN orders ON(refunds.order_id = orders.entity_id)
WHERE (orders.entity_id = 3)
GROUP BY Method
union
SELECT invoices.method_in as Method, SUM(invoices.inv_value) AS
total_invoiced, 0 AS total_refunded
FROM invoices left JOIN orders ON(invoices.order_id = orders.entity_id)
WHERE (orders.entity_id = 3)
GROUP BY Method)main_table
GROUP BY Method
输出是我的预期。这是
我的问题是: 反正有没有重写我的查询,为了删除我的重复条件WHERE(orders.entity_id = 3),查询将是这样的
SELECT Method, SUM(total_invoiced), SUM(total_refunded)
FROM
(SELECT refunds.method_rf AS Method, 0 AS total_invoiced,
SUM(refunds.ref_value) AS total_refunded
FROM refunds LEFT JOIN orders ON(refunds.order_id = orders.entity_id)
GROUP BY Method
union
SELECT invoices.method_in as Method, SUM(invoices.inv_value) AS
total_invoiced, 0 AS total_refunded
FROM invoices left JOIN orders ON(invoices.order_id = orders.entity_id)
GROUP BY Method)main_table
"PUT YOUR CONDITION"
GROUP BY Method
答案 0 :(得分:1)
您应该使用union all
。 union
会导致删除重复项的开销。以下内容稍微简单一点 - 您不需要orders
表:
SELECT Method, SUM(total_invoiced), SUM(total_refunded)
FROM ((SELECT r.method_rf AS Method, 0 AS total_invoiced, SUM(r.ref_value) AS total_refunded
FROM refunds r
WHERE r.order_id = 3
GROUP BY i.Method
) UNION ALL
(SELECT i.method_in as Method, SUM(i.inv_value) AS total_invoiced, 0 AS total_refunded
FROM invoices i
WHERE i.order_id = 3
GROUP BY i.Method
)
) ir
GROUP BY Method;
出于性能原因,我会在每个子查询中保留过滤器。如果您只关心一个订单,那么在聚合之前进行过滤是一种胜利表现。