与分组和派生表的多个连接

时间:2014-01-28 17:07:54

标签: mysql sql join group-by derived-table

我有四个MySQL表:联系人,订单,ordered_products和产品,我正在尝试编写一些报告查询。这是其中之一:

SELECT t1.name, t1.contact_id, SUM(t1.prodSoldQty) AS contactSoldQty, SUM(t1.prodSoldVol) AS soldVol
FROM contacts
INNER JOIN
(
 SELECT 
    contacts.name,
        ordered_products.product_id,
        ordered_products.contact_id,
        SUM(ordered_products.quantity) AS prodSoldQty,
        (products.price * SUM(ordered_products.quantity)) AS prodSoldVol
 FROM ordered_products
 INNER JOIN contacts ON contacts.id = ordered_products.contact_id
 INNER JOIN products ON products.id = ordered_products.product_id
 INNER JOIN orders ON orders.id = ordered_products.order_id
 GROUP BY ordered_products.product_id , ordered_products.contact_id
 ORDER BY ordered_products.product_id
) AS t1 ON t1.contact_id = contacts.id
GROUP BY contacts.id
ORDER BY t1.name;

一切都按预期工作,虽然我添加(并且我需要添加)另一个[LEFT | INNER] JOIN(例如:INNER JOIN命令ON orders.contact_id = contacts.id)行SUM总数搞砸了(它们似乎重复,一式三份......相应于订单的数量)。我想问题可能是第一个连接派生表中的多个分组。但它让我望而却步。在这里,您可以找到上述查询的略微变体。即便是这种微小的修改也能够触发“问题”:

SELECT t1.name, t1.contact_id,
SUM(t1.prodSoldQty) AS contactSoldQty,
SUM(t1.prodSoldVol) AS soldVol
FROM contacts
INNER JOIN
(
 SELECT 
    contacts.name,
        ordered_products.product_id,
        ordered_products.contact_id,
        SUM(ordered_products.quantity) AS prodSoldQty,
        (products.price * SUM(ordered_products.quantity)) AS prodSoldVol
 FROM ordered_products
 INNER JOIN contacts ON contacts.id = ordered_products.contact_id
 INNER JOIN products ON products.id = ordered_products.product_id
 INNER JOIN orders ON orders.id = ordered_products.order_id
 GROUP BY ordered_products.product_id , ordered_products.contact_id
 ORDER BY ordered_products.product_id
) AS t1 ON t1.contact_id = contacts.id
INNER JOIN orders ON orders.contact_id = contacts.id
WHERE orders.order_state_id != '111'
GROUP BY contacts.id
ORDER BY t1.name;

上述路径是死路一条。在@Gordon Linoff的帮助下,我找到了更好的方法。其中一个报告目标是计算总产品成本金额&客户/联系人基础上的总产品销售额。我专注于通过两个单独的连接来做到这一点。似乎一个人就足够了(避免包括几次几乎相同的表):

SELECT t1.name, t1.contact_id,
SUM(t1.prodSellQty) AS sellQty,
SUM(t1.prodCostVol) AS costAmount,
SUM(t1.prodSellVol) AS sellAmount
FROM contacts
INNER JOIN
(
 SELECT 
    contacts.name,
        ordered_products.contact_id,
        SUM(ordered_products.quantity) AS prodSellQty,
        SUM(products.price * ordered_products.quantity) AS prodCostVol,
        SUM(ordered_products.price * ordered_products.quantity) AS prodSellVol
 FROM ordered_products
 INNER JOIN contacts ON contacts.id = ordered_products.contact_id
 INNER JOIN products ON products.id = ordered_products.product_id
 INNER JOIN orders ON orders.id = ordered_products.order_id
 GROUP BY ordered_products.product_id , ordered_products.contact_id
 ORDER BY ordered_products.product_id
) AS t1 ON t1.contact_id = contacts.id
GROUP BY contacts.id
ORDER BY contacts.name;

谢谢,卢卡

0 个答案:

没有答案