mysql查询不起作用

时间:2011-07-03 19:04:39

标签: mysql

我正在处理一个连接几个表的查询。这是代码。 查询工作正常,直到我添加第三行SUM(SaleItems_T.qtymajor)AS销售。我收到一条错误消息 '字段列表'中的未知列'SaleItems_T.qtymajor' 我正在尝试构建一个重新排序工作表。非常感谢帮助。

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

3 个答案:

答案 0 :(得分:3)

您没有在FROM子句中或通过JOIN在查询中引用SaleItems_T表。

答案 1 :(得分:1)

这是您的查询错误的地方:

FROM ProductMaster_T, StockMain_T, stockbuffers_T, stkbalance_T

将其更改为:

FROM ProductMaster_T, StockMain_T, stockbuffers_T, stkbalance_T, SaleItems_T

答案 2 :(得分:0)

(请不要投票。我只是把它放在这里,因为评论空间不适合这么长的评论。)

您应该使用显式JOIN ... ON join_condition语法而不是通过WHERE条件隐式JOIN(这是很老的方法)。它更好,因为很难忘记一个条件(或一个表,就像你做的那样!),因此不容易出错。它还将连接条件(几乎每个查询中都使用它)与您在各种查询中可能具有的其他条件分开。

所以,而不是

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