在sql中加入,联合3个表

时间:2017-11-05 17:20:16

标签: sql database

请帮我解决我的sql问题。 在我的数据库中,我有3个表如下 enter image description here

我写了一个查询,显示退款总额和总发票金额,该方法已用于特定订单的退款或发票(现金,信用卡或结账)。

我的查询如下:

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

输出是我的预期。这是

output

我的问题是: 反正有没有重写我的查询,为了删除我的重复条件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

1 个答案:

答案 0 :(得分:1)

您应该使用union allunion会导致删除重复项的开销。以下内容稍微简单一点 - 您不需要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;

出于性能原因,我会在每个子查询中保留过滤器。如果您只关心一个订单,那么在聚合之前进行过滤是一种胜利表现。