2011-07-03 161 views
1

我正在處理連接多個表的查詢。這裏是代碼。 查詢工作正常,直到我添加第三行SUM(SaleItems_T.qtymajor)AS銷售。我收到一條錯誤消息,其中說 「字段列表」中的未知列'SaleItems_T.qtymajor' 我正在嘗試構建重新排序工作表。非常感謝。mysql查詢不起作用

SELECT ProductMaster_T.ProductName_VC AS PGroup, 
StockMain_T.ItemDescription AS Item, 
SUM(SaleItems_T.qtymajor) AS sales, 
stockbuffers_T.buffer_qty AS BufferQty, 
(stkbalance_T.AJ1+stkbalance_T.AR2+stkbalance_T.AD3+stkbalance_T.DX4) AS Stock, 
(stkbalance_T.AJ1+stkbalance_T.AR2+stkbalance_T.AD3+stkbalance_T.DX4)-stockbuffers_T.buffer_qty AS Result 
FROM ProductMaster_T, StockMain_T, stockbuffers_T, stkbalance_T 
WHERE StockMain_T.ItemCode = stockbuffers_T.itemcode 
AND 
StockMain_T.ItemCode = stkbalance_T.itemid 
AND 
ProductMaster_T.ProductID = StockMain_T.ProdID 
AND 
SaleItems_T.ItemID = StockMain_T.ItemCode 
ORDER BY 
ProductName_VC,ItemDescription ASC 
+0

@awerti saleItems_T的表結構如下 INV,項目,qtymajor,計量單位,價格。每一件物品都會添加一行 – mmdel

回答

3

您尚未在查詢中引用SaleItems_T表,無論是在FROM子句中還是通過JOIN。

+0

謝謝,我剛剛補充說。現在查詢正在工作,但只是給出一行結果。我有3500件商品,如果有任何商品,我想顯示每件商品的總銷售額。 – mmdel

+2

@mmdel:如果您希望爲每個項目設置SUM,請添加「GROUP BY StockMain_T.ItemCode」。或「GROUP BY ProductMaster_T.ProductID」,無論哪一個唯一確定您的項目。 –

+0

@ypercube非常感謝。查詢現在工作正常。 – mmdel

1

這是你的查詢是錯誤的:

FROM ProductMaster_T, StockMain_T, stockbuffers_T, stkbalance_T 

修改成:

FROM ProductMaster_T, StockMain_T, stockbuffers_T, stkbalance_T, SaleItems_T 
0

(請沒有投票權爲了這個,我只是把它放在這裏的評論空間是不適合FOT這樣很長的意見。)

你應該真的使用明確的JOIN ... ON join_condition語法,而不是通過WHERE條件隱式加入(這是很舊的方式來做到這一點)。這更好,因爲很難忘記一個條件(或者一張表,就像你做的那樣!),因此不太容易出錯。它還會將您在各種查詢中可能遇到的其他條件(幾乎在每個查詢中將使用這些條件)分開。

所以,與其

FROM ProductMaster_T, StockMain_T 
WHERE ProductMaster_T.ProductID = StockMain_T.ProdID 

寫:

FROM ProductMaster_T 
    JOIN StockMain_T 
    ON ProductMaster_T.ProductID = StockMain_T.ProdID 

這也是很好用別名(與(可選的)AS關鍵字)。它使代碼更易讀:

FROM ProductMaster_T AS p 
    JOIN StockMain_T AS m 
    ON p.ProductID = m.ProdID 

整個查詢可以寫成:

SELECT 
    master.ProductName_VC AS PGroup, 
    main.ItemDescription AS Item, 
    SUM(items.qtymajor) AS sales, 
    buf.buffer_qty  AS BufferQty, 
    (bal.AJ1 + bal.AR2 + bal.AD3 + bal.DX4) 
     AS Stock, 
    (bal.AJ1 + bal.AR2 + bal.AD3 + bal.DX4) - buf.buffer_qty 
     AS Result 
FROM ProductMaster_T AS master 
    JOIN StockMain_T AS main 
     ON master.ProductID = main.ProdID 
    JOIN stockbuffers_T AS buf 
     ON main.ItemCode = buf.itemcode 
    JOIN stkbalance_T AS bal 
     ON main.ItemCode = bal.itemid 
    JOIN SaleItems_T AS items 
     ON items.ItemID = main.ItemCode 
ORDER BY 
    ProductName_VC ASC, 
    ItemDescription ASC 
GROUP BY ??? main.ItemCode ??? --- depends on your tables' 
            --- relationships