MySQL总和来自两个连接表和多行

时间:2012-12-21 14:30:17

标签: mysql join sum

我遇到以下问题的问题:

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'中包含多个商品,则上述总和会多次计算'订单'中的邮资。

如何重写此查询以便邮资只计算一次?

非常感谢您的任何帮助。

3 个答案:

答案 0 :(得分:2)

您不需要子查询,只需将postage_price和vat移出聚合和GROUP BY:

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 

答案 1 :(得分:1)

您需要添加分组

GROUP BY ordered_items.order_id

答案 2 :(得分:0)

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