MySQL用sum加速子查询

时间:2017-05-09 16:27:30

标签: mysql sql join subquery

我需要一个查询来获取实际库存的概览(每个唯一产品ID只有一行)以及所有销售和采购订单。现在,我们使用两个子查询(销售和采购订单),因为可能有多个销售和采购订单。 由于有两个子查询,此查询非常慢。是否有另一种方法可以获得销售订单的总和和采购订单的总和,例如常规的左连接?

当前查询

SELECT stock.quanity, salesOrders.quantity, purchaseOrders.quantity
FROM stock
LEFT JOIN (
   SELECT product_id, sum(quantity) as quantity
   FROM sales_orders
   GROUP BY product_id
) salesOrders ON stock.product_id=salesOrders.product_id
LEFT JOIN (
   SELECT product_id, sum(quantity) as quantity
   FROM purcahse_orders
   GROUP BY product_id
) purchaseOrders ON stock.product_id=purchaseOrders.product_id

1 个答案:

答案 0 :(得分:3)

相关的子查询可能会更快,具有正确的索引:

SELECT s.quantity, 
       (SELECT sum(so.quantity) FROM sales_orders so WHERE s.product_id = so.product_id
       ) as sales_quantity ,
       (SELECT sum(po.quantity) FROM purchase_orders po WHERE s.product_id = po.product_id
       ) as purchase_quantity 
FROM stock s ;

为了有希望提高效果,您需要sales_orders(product_id, quantity)purchase_orders(product_id, quantity)上的索引。