一对多加入,两个表中的Sum

时间:2014-12-12 20:06:00

标签: mysql sql mysql-5.5

我有两个表订单和ordersdetail有数百万行..

表:

订单 - id(主键),金额,日期(索引)

orderdeails - id(主键),skunitid,数量,order_id(索引)

一个订单有多个订单明细...

查询:

Select Sum(orders.amount),SUM(ordersdetails.quantity)
from orders join orderdetails on ordersdetail.order_id = orders.id 
where {{conditios on date column of order table}}

我查了错误的查询,我想在单个查询(单次迭代)中数量和数量之和,但是当我使用连接顺序时,表的数量来得那么多。我在订单表中的日期列索引,所以我必须从订单表开始查询(表中的百万行。)

我必须要有效率..

1 个答案:

答案 0 :(得分:0)

Select 
   Sum(Order.Amount),
   Sum(OrderTotals.OrderQuantity)
From
   Order
Inner join
( 
   Select
       OrderDetails.OrderID,
       Sum(OrderDetails.Quantity) as OrderQuantity
   From
       OrderDetails 
   Where
       OrderDetails.OrderID in
       (Select OrderID From Order where Order.Date between @x and @y)

   Group by
       OrderDetails.OrderID
) As OrderTotals
On 
    OrderTotals.OrderID = Order.OrderID

Where
   Order.Date between @x and @y