MySQL GROUP BY和SELECT GROUP BY

时间:2013-12-07 01:05:40

标签: mysql select group-by

这是我的表

产品: enter image description here

订单

enter image description here

这是我的问题:

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

结果:

enter image description here

如果您注意到小计,则仅计算取决于所选行。如何使用相同的order_id添加其他行的结果?

2 个答案:

答案 0 :(得分:1)

我还没有对此进行测试,但我认为这正是您所寻找的。

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)

由于您说您想要小计,我假设您只想计算订单表每行的值。为此,您必须删除DISTINCTGROUP BY。 (DISTINCTGROUP 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
相关问题