0

我有两个工作查询:

第一个返回产品列表:

$sql = "
   SELECT a.stockID, a.stockCatID, a.stockName, a.stockCode, a.stockCatCode,
   CONCAT_WS(' » ', d.stockCatName, c.stockCatName, b.stockCatName) AS stockPath,
   a.stockName AS stockTitle, a.stockID AS uniStock
   FROM stockcards a
   LEFT OUTER JOIN stockcategories b
     ON a.stockCatID = b.stockCatID
   LEFT OUTER JOIN stockcategories c
     ON b.stockParentCat = c.stockCatID
   LEFT  OUTER JOIN stockcategories d
     ON c.stockParentCat = d.stockCatID ";

第二个基本上是返回总接收和总发送的差异,即剩余数量:

SELECT DISTINCT (COALESCE(o.totalReceived, 0) + COALESCE(p.totalSent, 0)) as RemainingStock
 FROM deliverydetails k 
 INNER JOIN stockcards l ON k.stockID= l.stockID
 LEFT JOIN
     (
         SELECT m.stockID, SUM(m.dQuantity) totalReceived
         FROM deliverydetails m
         WHERE m.dQuantity > 0
         GROUP BY m.stockID
     )
     o ON k.stockID = o.stockID
 LEFT JOIN
     (
         SELECT n.stockID, SUM(n.dQuantity) totalSent
         FROM deliverydetails n
         WHERE n.dQuantity < 0
         GROUP BY n.stockID
     )
     p ON k.stockID = p.stockID

我需要在第一个查询中添加一个新列以显示剩余数量。但是没能成功加入这两个。感谢您的任何提示。

4

1 回答 1

0

看起来您的第二个查询只是将每个 stockID 的正负 dQuantities 相加,然后将它们加在一起,我认为对您的第一个查询的这个小改动就足够了:

SELECT a.stockID, a.stockCatID, a.stockName, a.stockCode, a.stockCatCode,
   CONCAT_WS(' » ', d.stockCatName, c.stockCatName, b.stockCatName) AS stockPath,
   a.stockName AS stockTitle, a.stockID AS uniStock,
   dd.RemainingStock AS RemainingStock 
   FROM stockcards a
   LEFT OUTER JOIN stockcategories b
     ON a.stockCatID = b.stockCatID
   LEFT OUTER JOIN stockcategories c
     ON b.stockParentCat = c.stockCatID
   LEFT  OUTER JOIN stockcategories d
     ON c.stockParentCat = d.stockCatID
   LEFT OUTER JOIN 
     (SELECT stockID, SUM(dQuantity) AS RemainingStock
     FROM deliverydetails
     GROUP BY stockID) AS dd
   ON dd.stockID = a.stockID
于 2013-01-20T17:30:37.203 回答