这是我的表
产品:
订单
这是我的问题:
SELECT DISTINCT
orders.*,
IF (orders.price_type = 1, products.price * orders.quantity, products.discount_price * orders.quantity) AS subtotal
FROM
orders
LEFT JOIN
products
ON
orders.product_id = products.id
GROUP BY
order_id
结果:
如果您注意到小计,则仅计算取决于所选行。如何使用相同的order_id
添加其他行的结果?
答案 0 :(得分:1)
我还没有对此进行测试,但我认为这正是您所寻找的。 p>
SELECT DISTINCT
orders.*,
sum(IF (orders.price_type = 1, products.price * orders.quantity, products.discount_price * orders.quantity)) AS subtotal
FROM
orders
LEFT JOIN
products
ON
orders.product_id = products.id
GROUP BY
order_id
答案 1 :(得分:0)
由于您说您想要小计,我假设您只想计算订单表每行的值。为此,您必须删除DISTINCT
和GROUP BY
。 (DISTINCT
和GROUP BY
对于这样的事情有点奇怪,如果你想要用小计返回每一行,你就不需要它们了:
SELECT orders.*,
IF(orders.price_type = 1,
products.price * orders.quantity,
products.discount_price * orders.quantity) AS subtotal
FROM orders
LEFT JOIN products ON orders.product_id = products.id
这将为您提供订单表中每一行的小计。
如果您想要结果GROUPED BY order_id
,则无法真正执行SELECT *
,因为GROUP BY会对其他列做出错误的假设,并且您最终会得到错误的结果,就像您所经历的那样。你可以这样做:
SELECT orders.order_id,
orders.order_date,
SUM(IF(orders.price_type = 1,
products.price * orders.quantity,
products.discount_price * orders.quantity)) AS subtotal
FROM orders
LEFT JOIN products ON orders.product_id = products.id
GROUP BY orders.order_id, orders.order_date