SQL错误 - 字段可以引用多个表

时间:2012-08-30 15:40:07

标签: sql compiler-errors ms-access-2010

我无法理解为什么我会收到错误

"指定的字段qb2.WellworkOIL可以引用SQL语句中FROM子句中列出的多个表"

基于以下查询

SELECT 
    qb1.CompanyName, 
    qb1.AssetName, 
    qb1.Year, 
    IIf(qb1.PrimaryProductionType='Oil', 
        qb2.WellworkOIL, 
        IIF(qb1.PrimaryProductionType='Gas', 
            qb3.WellworkGAS, 
            qb4.WellworkOilGas)) AS Selected
FROM 
    (
        (
            PEBaseQueryConditions AS qb1 
            INNER JOIN PE_Field_WellworkOIL AS qb2 
            ON (qb1.Year=qb2.Year) AND (qb1.AssetName=qb2.AssetName)
        ) 
        INNER JOIN PE_Field_WellworkGAS AS qb3 
        ON (qb1.Year=qb3.Year) AND (qb1.AssetName=qb3.AssetName)
    ) 
    INNER JOIN PE_Field_WellworkOILGAS AS qb4 
    ON (qb1.Year=qb4.Year) AND (qb1.AssetName=qb4.AssetName)
GROUP BY 
    qb1.CompanyName, 
    qb1.AssetName, 
    qb1.Year, 
    qb1.PrimaryProductionType,
    qb2.WellworkOIL, 
    qb3.WellworkGAS, 
    qb4.WellworkOilGas;

2 个答案:

答案 0 :(得分:0)

我认为摆脱你的GROUP BY条款可以消除这个问题。您没有使用聚合函数,因此不需要分组。

SELECT 
    qb1.CompanyName, 
    qb1.AssetName, 
    qb1.Year, 
    IIf(qb1.PrimaryProductionType='Oil', 
        qb2.WellworkOIL, 
        IIF(qb1.PrimaryProductionType='Gas', 
            qb3.WellworkGAS, 
            qb4.WellworkOilGas)) AS Selected
FROM    PEBaseQueryConditions AS qb1 
            INNER JOIN PE_Field_WellworkOIL AS qb2 
                 ON (qb1.Year=qb2.Year) AND (qb1.AssetName=qb2.AssetName)
            INNER JOIN PE_Field_WellworkGAS AS qb3 
                 ON (qb1.Year=qb3.Year) AND (qb1.AssetName=qb3.AssetName)
            INNER JOIN PE_Field_WellworkOILGAS AS qb4 
                 ON (qb1.Year=qb4.Year) AND (qb1.AssetName=qb4.AssetName)

答案 1 :(得分:0)

没有时间尝试这个(如果这不起作用,请道歉)但我之前没有看到别名语法(我认为你不需要“AS”) - 试试这个;

SELECT qb1.CompanyName, qb1.AssetName, qb1.Year, 
       IIf(qb1.PrimaryProductionType='Oil', qb2.WellworkOIL, 
             IIF(qb1.PrimaryProductionType='Gas', qb3.WellworkGAS, 
                           qb4.WellworkOilGas)) AS Selected

FROM PEBaseQueryConditions qb1 
INNER JOIN PE_Field_WellworkOIL qb2 ON (qb1.Year=qb2.Year AND qb1.AssetName=qb2.AssetName)
INNER JOIN PE_Field_WellworkGAS qb3 ON (qb1.Year=qb3.Year AND qb1.AssetName=qb3.AssetName) 
INNER JOIN PE_Field_WellworkOILGAS qb4 ON (qb1.Year=qb4.Year AND qb1.AssetName=qb4.AssetName)

另外,根据Jon Woo的建议,如果您没有使用聚合函数(例如COUNT,SUM ......),则不需要“分组依据”

编辑:您也可能会丢失一些括号