加入两个独立查询的结果

时间:2013-01-20 17:08:19

标签: mysql sql join

我有两个工作查询:

1st返回产品清单:

$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

我需要在第一个查询中添加一个新列以显示重新定量数量。但无法成功加入这两个。谢谢你的任何提示。

1 个答案:

答案 0 :(得分: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