如何加入MS Access中的功能?

时间:2014-05-20 02:32:20

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

我正在尝试在MS Access查询中向JOIN条件添加一个函数。

作为简化示例,请考虑我:

tblChild以及tblParenttblGrandparent

tblChild同时具有可为空的ParentIdGrandparentId,具体取决于哪一个已知。我正在尝试编写一个查询来获取更具体的关系。如果这是TSQL,那将是:

SELECT
    columns
FROM
    tblChild AS c
LEFT OUTER JOIN
    tblParent AS p
        ON p.[Id] = c.[ParentId]
LEFT OUTER JOIN
    tblGrandparent AS gp
        ON gp.[Id] = COALESE(p.[GrandParentId], c.[GrandParentId])

但是我无法弄清楚如何在Access中的COALESCE条件中获得JOIN样式函数。这是我期望的工作:

SELECT
    columns
FROM
    (tblChild AS c
LEFT OUTER JOIN
    tblParent AS p
        ON p.[Id] = c.[ParentId])
LEFT OUTER JOIN
    tblGrandparent AS gp
        ON gp.[Id] = Nz(p.[GrandParentId], c.[GrandParentId])

1 个答案:

答案 0 :(得分:1)

我希望NZ()能够正常运作。但您可以使用or吗?

SELECT columns
FROM (tblChild AS c LEFT JOIN
      tblParent AS p
      ON p.[Id] = c.[ParentId]
     ) LEFT JOIN
    tblGrandparent AS gp
    ON (gp.[Id] = p.[ParentId] or gp.[Id] = c.[GrandParentId]);

这并不完全相同。形式上,最后一个条件是:

    ON (gp.[Id] = p.[ParentId] or gp.[Id] = c.[GrandParentId] and gp.[Id] <> p.[ParentId]);

编辑:

另一种方法是两个连接:

SELECT columns
FROM ((tblChild AS c LEFT JOIN
       tblParent AS p
       ON p.[Id] = c.[ParentId]
      ) LEFT JOIN
     tblGrandparent AS gp
     ON (gp.[Id] = p.[ParentId])
    ) LEFT JOIN
    tblGrandparent AS gp2
    ON gp.[Id] = c.[GrandParentId]);

然后你必须调整&#34;列&#34;根据情况从gpgp2提取。