我有两个表订单和订单项。 订单表具有ID,order_total,receiveved_amount orderitems表具有id,order_id,名称,total_item
我想要订单表中的receved_amount的总和,order_total以及订单项的total_item的总和。所以我用
SELECT SUM(`received_amount`) as totalRecieved,
SUM(`order_total`) as orderTotal
FROM `orders` AS `Order`
LEFT JOIN `order_items` AS `OrderItems`
ON (`OrderItems`.`order_id`=`Order`.`id`)
和
SELECT SUM(`received_amount`) as totalRecieved,
SUM(`order_total`) as orderTotal
FROM `orders` AS `Order`
LEFT JOIN `order_items` AS `OrderItems`
ON (`OrderItems`.`order_id`=`Order`.`id`)
group by order.id
但是他们都没有给我正确的结果。
答案 0 :(得分:1)
您正在聚合数据层次结构的两个级别。对于每个订单,这都会导致笛卡尔积的问题。
解决方案是在进行order_items
之前,先在join
上进行聚合:
SELECT SUM(received_amount) as totalRecieved,
SUM(order_total) as orderTotal
FROM orders o LEFT JOIN
(SELECT oi.order_id, SUM(total_items) as total_items
FROM order_items oi
GROUP BY oi.order_id
) oi
ON oi.order_id = o.id;
答案 1 :(得分:0)
作为替代方案,您可以受益于cte结构或如下所示的临时表:
;with cte (order_id, SumTotalItems) as (
SELECT oi.order_id, SUM(total_items) as SumTotalItems
FROM order_items oi
GROUP BY oi.order_id
)
select sum(o.receivedamount) as SumReceivedAmount
, sum(o.order_total) as SumOrderTotal
, cte.SumTotalItems
from orders o
left outer join cte on o.id = cte.order_id