具有许多连接的复杂查询

时间:2011-11-18 14:29:49

标签: mysql django group-by inner-join

我正在尝试进行一次查询,以便从数据库中获取一些统计数据。

我在这里描述的表结构:

PRODUCTS
id | price | buy_price | vendor_code | ...

ORDERS
id | shipping_method_id | ...

ORDER_ITEMS
id | order_id | product_id | quantity | ...

SHIPPING_METHODS
id | cost | ...

SUPPLIERS
id | code | ...

我想获得这样的数据。换言之,我正在报告我的电子商务中的产品总收入,费用和购买数量,并希望他们按供应商分组。我写了这个sql:

SELECT orders.id,
suppliers.code,
COUNT(products.id)*items.quantity buys,
SUM(products.price*items.quantity + shipping_methods.cost) sales,
SUM(products.buy_price*items.quantity) expenses
FROM `orders` orders
INNER JOIN `order_items` items ON items.order_id = orders.id
INNER JOIN `products` products ON items.product_id = products.id
INNER JOIN (SELECT DISTINCT suppliers.code FROM `suppliers`) suppliers
    ON products.vendor_code LIKE CONCAT(suppliers.code, '%%')
INNER JOIN `shipping_methods` shipping_methods ON orders.shipping_method_id = shipping_methods.id
WHERE (
    orders.delivery_date_to BETWEEN '2011-11-18' AND '2011-11-19'
)
GROUP BY suppliers.code, orders.id
ORDER BY buys DESC

这回到我这个数据:

order_id    code    buys    sales   expenses
85          SB      4       1504    1111.32
84          VD      2       496     350.82
60          lg      2       1418    1052.31
88          SB      1       376     277.83

当我将GROUP BY suppliers.code, orders.id更改为GROUP BY suppliers.code时,它会返回几乎正确的数据,我的意思是数据按代码分组,但计数错误。承认销售和费用是正确的

order_id    code    buys    sales   expenses
85          SB      8       1880    1389.15
60          lg      2       1418    1052.31
84          VD      2       496     350.82

如果你看到SB计算总共8个销售额,但实际上只有5个,正如你在前面的表中看到的那样。我确定我在查询中遗漏了一些内容,但无法理解如何纠正这一点。

PS字段order_id在我的进一步脚本中未使用,我使用它是因为django的Model.objects.raw()查询确实需要在结果中有主键,不明白为什么

1 个答案:

答案 0 :(得分:1)

尝试此查询。

SELECT t1.code, SUM(t1.buys), SUM(t1.sales) FROM (
SELECT orders.id, 
suppliers.code, 
COUNT(products.id)*items.quantity buys, 
SUM(products.price*items.quantity + shipping_methods.cost) sales, 
SUM(products.buy_price*items.quantity) expenses 
FROM `orders` orders 
INNER JOIN `order_items` items ON items.order_id = orders.id 
INNER JOIN `products` products ON items.product_id = products.id 
INNER JOIN (SELECT DISTINCT suppliers.code FROM `suppliers`) suppliers 
    ON products.vendor_code LIKE CONCAT(suppliers.code, '%%') 
INNER JOIN `shipping_methods` shipping_methods ON orders.shipping_method_id = shipping_methods.id 
WHERE ( 
    orders.delivery_date_to BETWEEN '2011-11-18' AND '2011-11-19' 
) 
GROUP BY suppliers.code, orders.id 
ORDER BY buys DESC 
) AS t1
GROUP BY t1.code

编辑:我忘记了SUM()部分。刚添加,如果您已经尝试过,请重试。