mysql 查询给出了五个表的错误结果

mysql query gives wrong results from five tables

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

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

我的数据库表是:

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
.......

感谢:

如果两个 table 具有相同 ID 的多行,您可以 运行 解决 bad/false sum() 值的问题,您可以获得笛卡尔 sum()结果。为帮助解决此问题,请预先查询每个 table 的聚合,以便每个 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