【问题标题】:MySQL GROUP BY and SELECT GROUP BY [duplicate]MySQL GROUP BY 和 SELECT GROUP BY [重复]
【发布时间】:2013-12-07 01:05:39
【问题描述】:

这是我的桌子

产品:

订单

这是我的查询:

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 的其他行的结果?

【问题讨论】:

    标签: mysql select group-by


    【解决方案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
    

    【讨论】:

    • 我不确定这个解决方案。它仍然返回相同数量的行,但它肯定会给出每个 order_id 的总数,但其余列仅与一个订单行相关。但如果它被接受了,我还能说别的吗
    【解决方案2】:

    既然你说你想要小计,我假设你只想计算订单表每一行的值。为此,您必须删除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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-20
      • 1970-01-01
      • 2018-05-18
      • 2018-06-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多