MySQL:不包括首次出现的总和数量

时间:2017-07-21 09:55:54

标签: php mysql sum

我有一个电子商务网站的三张桌子。

orders(id)

products(id, name)

order_products(id, order_id, product_id, quantity)

我需要总结每种产品的总销量,但有一个条件:

  • 仅在产品订购多次后才会生效。

我已经通过计算每种产品的总订单并设置条件HAVING COUNT(orders.id) > 1

来完成此操作

我面临的问题是,当我对每种产品的数量求和时,我需要排除第一个订单的数量。

这是我的简化查询

SELECT
    order_products.*,
    COUNT(orders.id) tot_orders,
    SUM(order_products.quantity) tot_ordered
FROM order_products
LEFT JOIN orders ON order_products.order_id = orders.id
GROUP BY order_products.product_id
HAVING tot_orders > 1
ORDER BY tot_ordered DESC

这仅显示已订购多次的产品(如多个订单,不超过一个数量),但数量总和仍考虑第一个订单,我不想要。 / p>

是否有可能在此查询中减去这些数量?我希望在循环结果时避免再做一次查询。

谢谢

编辑以下是示例

  • 订单n1:

    • product_1 qta 1
    • product_2 qta 2
    • product_3 qta 1
  • 订单n2:

    • product_1 qta 1
    • product_2 qta 1

我期待的结果是:

  • product_1 qta 1
  • product_2 qta 1

基本上我只计算了那些订购多件商品的数量,不包括第一个订单(product_1和product_2已计算,product_3尚未计算,因为它只订购了一个)

EDIT2 / SOLUTION 好吧,我想我想通了。我在原始查询中添加了一个只查询第一个订单数量的子查询,而不是从总数量中减去这个值。这是子查询

(
    SELECT
        SUM(first_product.quantity)
    FROM order_products first_product
    LEFT JOIN orders ON first_product.order_id = orders.id
    WHERE first_product.id = order_products.id
) first_order_qta

order_products.id引用外部表,而不是子查询中的表。

2 个答案:

答案 0 :(得分:1)

试试这个,我在当地检查一下就可以了。

SELECT
    order_products.*,
    COUNT(orders.id) tot_orders,
    SUM(order_products.quantity) tot_ordered - (SELECT op.quantity from order_products op WHERE op.product_id = order_products.product_id ORDER BY created_on LIMIT 0,1)
FROM order_products
LEFT JOIN orders ON order_products.order_id = orders.id
GROUP BY order_products.product_id
HAVING tot_orders > 1
ORDER BY tot_ordered DESC

答案 1 :(得分:0)

在我看来,你只是混淆了tot_orderstot_ordered

SELECT order_products.*
         , COUNT(orders.id) tot_orders
         , SUM(order_products.quantity) tot_ordered
FROM order_products
LEFT JOIN orders ON order_products.order_id = orders.id
GROUP BY order_products.product_id
HAVING tot_ordered > 1
ORDER BY tot_ordered DESC 

如果您想减去第一个订单,请尝试:

SELECT order_products.*
     , COUNT(orders.id) tot_orders
     , SUM(order_products.quantity) - 1 tot_ordered
FROM order_products
LEFT JOIN orders ON order_products.order_id = orders.id
GROUP BY order_products.product_id
HAVING tot_ordered > 1
ORDER BY tot_ordered DESC

编辑:我做了第三个查询,以便从总数量中减去订单数量:

SELECT OP_ID
     , OP_OID
     , OP_PID
     , tot_ordered - tot_orders AS qta
FROM (
    SELECT op.id OP_ID
         , op.order_id OP_OID
         , op.product_id OP_PID
         , COUNT(orders.id) tot_orders
         , SUM(op.quantity) tot_ordered
    FROM order_products op
    LEFT JOIN orders ON order_products.order_id = orders.id
    ) base
GROUP BY order_products.product_id
HAVING base.tot_ordered > 1
ORDER BY qta DESC