1

我对以下查询有疑问:

SELECT sum(((ordered_items.price + ordered_items.vat) * ordered_items.qty) + orders.postage_price + orders.postage_vat) as total_price
FROM orders
JOIN ordered_items
ON orders.id_orders = ordered_items.order_id
GROUP BY orders.id_orders

我们的想法是恢复包括邮资在内的订单总价。

  • ordered_items - 包括所有订购的物品(所以可以有多行)
  • 订单 - 包括订单的邮费(这里每个订单只有一行)

我遇到的问题是,如果订单在“ordered_items”中包含多个项目,则上述总和多次计算“订单”中的邮资。

如何重写此查询,使邮资只计算一次?

非常感谢您的帮助。

4

3 回答 3

2

您不需要子查询,只需将 postage_price 和增值税移出聚合并按它们分组:

SELECT sum((ordered_items.price + ordered_items.vat) * ordered_items.qty) + orders.postage_price + orders.postage_vat as total_price
FROM orders
JOIN ordered_items
ON orders.id_orders = ordered_items.order_id
GROUP BY orders.postage_price, orders.postage_vat 
于 2012-12-21T14:41:11.350 回答
1
SELECT items.total + orders.postage_price + orders.postage_vat) AS total_price
FROM orders
JOIN (SELECT order_id, SUM((ordered_items.price + ordered_items.vat) * ordered_items.qty) AS total
    FROM ordered_items
    GROUP BY order_id) items
ON orders.id_orders = items.order_id
于 2012-12-21T14:34:03.093 回答
1

您需要添加分组

GROUP BY ordered_items.order_id
于 2012-12-21T14:34:05.980 回答