是否可以使用子查询而不是使用访问中的from子句中的表?

时间:2013-11-20 20:58:49

标签: sql ms-access subquery

在MS ACCESS中,是否可以:

使用子查询而不是from子句中的第一个表?

(以下代码根据帮助我的精彩人士的建议编辑)

示例:

Part 1 (now working):
    FROM
    (SELECT [Distributor2].PRODUCTCODE
      FROM [Distributor2]

      UNION

     SELECT [DISTRIBUTOR3].PRODUCTCODE
      FROM [DISTRIBUTOR3]

      UNION

     SELECT [DISTRIBUTOR1].PRODUCTCODE
      FROM [DISTRIBUTOR1]
    ) AS [ALLPRODUCTCODES]

包括第2部分(现在正在工作!甚至我的多个加入条件!!!)。我已将下面的ALLPRODUCTSCODES表重命名为“表1”,以便更清楚:

  FROM ((((subqueryabove) AS [TABLE1])
LEFT JOIN [TABLE2] on (Table2.productcode = Table1.productcode AND Table2.year=2013))
LEFT JOIN [TABLE3] on (Table3.productcode = Table1.productcode AND Table3.year=2013))
LEFT JOIN [TABLE4] on (Table4.productcode = Table1.productcode AND Table4.year=2013)

(从前两个回复的建议编辑的代码 - 感谢您对MSAccess支架疯狂的帮助!!!)

2 个答案:

答案 0 :(得分:3)

此查询触发“JOIN操作中的语法错误”,这可能令人费解,因为没有明确的JOIN参与。

SELECT sub.*
FROM
    (
        (SELECT 'a' AS fld1 FROM Dual)
        UNION ALL
        (SELECT 'b' AS fld1 FROM Dual)
        UNION ALL
        (SELECT 'c' AS fld1 FROM Dual)
    ) AS sub;

取消括起每个联合SELECT语句的括号,如下所示,允许查询无错误地运行。我怀疑你可能正在处理同样的问题 - 所以放弃你那些麻烦的括号。

SELECT sub.*
FROM
    (
        SELECT 'a' AS fld1 FROM Dual
        UNION ALL
        SELECT 'b' AS fld1 FROM Dual
        UNION ALL
        SELECT 'c' AS fld1 FROM Dual
    ) AS sub;

当你LEFT JOIN表的副词时它仍然可以工作。我在Access 2007中创建并测试了这个查询...

SELECT sub.*, tblFoo.id, tblFoo.some_text
FROM
    (
        SELECT 'a' AS fld1, 1 AS fld2 FROM Dual
        UNION ALL
        SELECT 'b' AS fld1, 2 AS fld2 FROM Dual
        UNION ALL
        SELECT 'c' AS fld1, 3 AS fld2 FROM Dual
    ) AS sub
    LEFT JOIN tblFoo
    ON sub.fld2 = tblFoo.id;

答案 1 :(得分:1)

是的,您当然可以以这种方式使用子查询。当涉及多个连接时,您的问题更可能是Access对括号有点挑剔。访问很容易在遇到

时抱怨

foo LEFT JOIN栏ON ... LEFT JOIN baz ON ...

希望看到

(foo LEFT JOIN栏ON ...)LEFT JOIN baz ON ...

修改

我看到这个问题变成了一个令人费解的问题。为了它的价值,我在Access 2010中对此进行了测试,它适用于我(实际表和字段名称):

SELECT u.PRODUCTCODE, [TABLE].productdescription
FROM
    (
            SELECT PRODUCTCODE FROM Distributor1
        UNION
            SELECT PRODUCTCODE FROM Distributor2
        UNION
            SELECT PRODUCTCODE FROM Distributor3
    ) AS u
    LEFT JOIN
    [TABLE]
        ON u.PRODUCTCODE = [TABLE].productcode