2013-01-20 105 views
0

我有兩個工作查詢:連接兩個獨立查詢的結果

1日返回產品列表:

$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 "; 

第二個是基本返回總接收和總的差異發送whic的剩餘量:

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 

我需要添加一個新的列到第一個查詢顯示remanining數量。但不能成功加入這兩個。感謝您的任何提示。

回答

0

,因爲它似乎是你的第二查詢只是總結正面和負面dQuantities每個stockID,然後將它們放在一起,我覺得這個小的變化,以您的第一個查詢是 所有需要:

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 
相關問題