MySQL Logic帮助

时间:2010-06-29 19:42:43

标签: mysql e-commerce

我有以下查询,效果很好。我有两个问题......

1)我可以在子查询中删除内部联接到order并将其重新绑定到主查询中吗?

2)我需要将返回值计入生成的所有值中。每件商品的价格仅存储在order_product中。我的表格结构如下......

顺序

id  |  account_id  |  price  |  tax  |  shipping_price

order_product

order_id  |  product_id  |  vehicle_id  |  quantity  |  price

我需要系统支持每个订单的多个RMA ......

order_return

id  |  status_id  |  order_id  |  account_id  |  timestamp

order_return_product

return_id  |  reason_id  |  product_id  |  vehicle_id  |  note  |  quantity

此查询生成销售统计信息,我需要它不考虑已返回的项目....

SELECT
                    SUM(price+shipping_price) AS total_sales,
                    COUNT(id) AS total_orders,
                    AVG(price+shipping_price) AS order_total_average,
                    (SELECT
                            SUM(quantity)
                        FROM `order_product`
                        INNER JOIN `order` ON (
                            `order`.id = order_product.order_id AND
                            `order`.created >= '.$startTimestamp.' AND
                            `order`.created <= '.$endTimestamp.' AND
                            `order`.type_id = '.$type->getId().' AND
                            `order`.fraud = 0
                        )
                    ) AS total_units,
                    SUM(price+shipping_price)/'.$dateDifference['total']['days'].' AS daily_average
                FROM `order`
                WHERE created >= '.$startTimestamp.' AND
                created <= '.$endTimestamp.' AND
                fraud = 0 AND
                type_id = '.$type->getId().'

1 个答案:

答案 0 :(得分:1)

我不太明白你为什么要形成内联系;您已经在查询ORDER表,因此您可以参考其中的当前行。也许以下会这样做?

SELECT
    SUM(price+shipping_price) AS total_sales,
    COUNT(id) AS total_orders,
    AVG(price+shipping_price) AS order_total_average,
    (SELECT
         SUM(quantity)
         FROM `order_product`
         WHERE `order`.id = order_product.order_id) AS total_units,
    SUM(price+shipping_price)/'.$dateDifference['total']['days'].' AS daily_average
FROM `order`
WHERE created >= '.$startTimestamp.' AND
      created <= '.$endTimestamp.'   AND
      fraud    = 0 AND
      type_id  = '.$type->getId().'

编辑:好的一点,我忽略了这一点。我建议添加一个子查询来查找返回的总数并在total_units计算中减去它,可能沿着以下行...

SELECT
SUM(price+shipping_price) AS total_sales,
COUNT(id) AS total_orders,
AVG(price+shipping_price) AS order_total_average,
((SELECT SUM(quantity)
      FROM `order_product`
      WHERE `order`.id = order_product.order_id) -
    (SELECT SUM (quantity)
         FROM order_return, order_return_product
         WHERE order_return.order_id = order.order_id AND
               order_return.id       = order_return_products.return_id))
   AS total_units,
SUM(price+shipping_price)/'.$dateDifference['total']['days'].' AS daily_average
FROM `order`
WHERE created    >= '.$startTimestamp.' AND
      created    <= '.$endTimestamp.'   AND
      fraud       = 0                   AND
      type_id  = '.$type->getId().'