mysql查询从五个表中得出错误的结果

时间:2015-01-13 18:53:40

标签: mysql join

我创建了一个mysql查询来生成我想要的结果。

实际上它给了我错误的结果。我的预期结果是通过从装运库存的SUM减去销售库存的总和来获得当前库存。

我的数据库表是:

items(itemId,itemUniqueNo,itemSize,itemColor....) prices(itemPrice,presentPriceBoolean,items_itemId....) shipments(shipmentDate,noOfPairs,items_itemId,sources_sourceId....) sources(sourceId,sourceName.....) solditems(quantitySold,items_itemId....)

我的查询如下:

SELECT itemId,itemUniqueNo,itemSize,itemGender,itemColor,sourceName,itemPrice,sourceName,
    (COALESCE(SUM(noOfPairs),0) - COALESCE(SUM(quantitySold),0)) AS quantityInStock
FROM(shoepalace.items 
    INNER JOIN shoepalace.prices ON items.itemId = prices.items_itemId AND presentPrice =1) 
    LEFT JOIN shipments ON shipments.items_itemId = items.itemId 
    INNER JOIN sources ON sources.sourceId = shipments.sources_sourceId 
    LEFT JOIN shoepalace.solditems ON items.itemId = solditems.items_itemId GROUP BY itemId

让我们说:

itemId       shipmentQuantity       quantitySold     finalQuantity(quantityInStock)
2            15                     3                12
3            10                     0                10
4            7                      4                3
.......

感谢:

1 个答案:

答案 0 :(得分:0)

如果两个表具有相同ID的多个行,则可能会遇到错误/错误sum()值的问题,您可以获得笛卡尔sum()结果。为了帮助解决这个问题,请从每个相应的表中预先查询聚合,这样每个ID只能获得一条记录(如果可以通过Coalesce测试获得),那么就抓住它。

SELECT 
      itemId,
      itemUniqueNo,
      itemSize,
      itemGender,
      itemColor,
      itemPrice,
      S1.sourceName,
      ( COALESCE( S1.ShipPairs ,0) 
      - COALESCE( S2.QtySold, 0) ) AS quantityInStock
   FROM
      shoepalace.items 
         INNER JOIN shoepalace.prices 
            ON items.itemId = prices.items_itemId AND presentPrice = 1
         LEFT JOIN 
            ( select items_itemId,
                     SUM(noOfPairs) as ShipPairs
                 from 
                    shipments 
                       INNER JOIN sources 
                          ON shipments.sources_sourceId = sources.sourceId
                 group by 
                    items_itemId ) as S1
            ON items.itemId = S1.items_itemId
         LEFT JOIN 
            ( select items_itemID,
                     SUM(QuantitySold) QtySold 
                 from 
                    solditems
                 group by
                    items_itemID ) S2
            ON items.itemId = S2.items_itemId