我正在尝试在MS Access查询中向JOIN
条件添加一个函数。
作为简化示例,请考虑我:
tblChild
以及tblParent
和tblGrandparent
tblChild
同时具有可为空的ParentId
和GrandparentId
,具体取决于哪一个已知。我正在尝试编写一个查询来获取更具体的关系。如果这是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])
答案 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;根据情况从gp
或gp2
提取。