从2个表中选择总和数量

时间:2017-09-27 09:31:23

标签: mysql sql

在MySQL中我有4个表:

or

我想从2个表格(order_detail_1,order_detail_2)按产品分组销售的产品数量总和

produt可以在order_detail_1中存在而不在order_detail_2中,反之亦然

我测试了这个查询并且它有效,但我想要一个没有联合和子查询的更简单的查询。

 - product(id)
 - order(id)
 - order_detail_1(id, product_id, order_id, qty)
 - order_detail_2(id, product_id, order_id, qty)

2 个答案:

答案 0 :(得分:2)

您似乎没有使用order表,而是检查它是否存在,因此您可以使用EXISTS()

SELECT p.product_id,sum(p.qty) as qty
FROM (SELECT product_id,qty,id_order FROM order_detail_1
      WHERE product_id IS NOT NULL
      UNION ALL 
      SELECT product_id,qty,id_order FROM order_detail_2
      WHERE product_id IS NOT NULL) p
WHERE EXISTS(SELECT 1 FROM order o 
             WHERE o.id = p.id_order)
GROUP BY p.product_id

答案 1 :(得分:0)

如果产品只在一个表格中,您可以使用left join

select p.id, (coalesce(sum(od1.qty), 0) + coalesce(sum(od2.qty, 0))) as qty
from product p left join
     order_detail_1 od1
     on od1.product_id = p.id left join
     order_detail_2 od2
     on od2.product_id = p.id
group by p.id;

这个表述取决于这两个表是排除的事实 - 产品只在一个表中。

编辑:

如果两个表中都有产品,那么您需要先将它们聚合起来:

select p.id, (coalesce(od1.qty, 0) + coalesce(od2.qty, 0)) as qty
from product p left join
     (select product_id, sum(qty) as qty
      from order_detail_1 od1
      group by product_id
     ) od1
     on od1.product_id = p.id left join
     (select product_id, sum(qty) as qty
      from order_detail_2 od2
      group by product_id
     ) od2
     on od2.product_id = p.id;