我进行了很多搜索,但无法对适用于MS Access的任何内容进行优化,我找到了SQL的解决方案,但Access SQL中不允许使用所使用的语句。
因此,在MS Access 2019中,我有一个带有ID和ParentID的表tbContentList。我想要显示特定父母的所有孩子/后代。
我的桌子看起来像这样:
如果我想显示所有Id 3的子代,我想得出的结果是:
MS访问查询中可能吗?VBA是可能的,但我认为使用查询可以更快。有人可以帮我这个话题吗?
SQL等效项:https: //www.codeproject.com/Articles/818694/SQL-Queries-to-Manage-Hierarchical-or-Parent-child (所有可能的子项)
因此,我能够修改Gustav的逻辑并使它适合我的项目。我将父结果放在定界符“;”之间。这样可以更轻松地在查询中查找特定ContentID的后代。此外,由于某些ContentID是树的开头,因此我不得不处理父列中的Null值。
Public Function GetParentIDs(ByVal lContentID As Long) As String
Static dbs As DAO.Database
Static tbl As DAO.TableDef
Static rst As DAO.Recordset
Dim strParents As String
If dbs Is Nothing Then
' For testing only.
' Replace with OpenDatabase of backend database file.
Set dbs = CurrentDb
Set tbl = dbs.TableDefs("tbContentList")
Set rst = dbs.OpenRecordset(tbl.Name, dbOpenTable)
End If
With rst
.Index = "PrimaryKey"
Do While lContentID > 0
.Seek "=", lContentID
If Not .NoMatch Then
lContentID = Nz(!ParentID.Value, 0)
If lContentID > 0 Then
strParents = ";" & CStr(lContentID) & strParents
Else
Exit Do
End If
Else
Exit Do
End If
Loop
' Leave recordset open.
' .Close
End With
' Don't terminate static objects.
' Set rst = Nothing
' Set tbl = Nothing
' Set dbs = Nothing
'Return value
If strParents = "" Then
GetParentIDs = ""
Else
GetParentIDs = strParents & ";"
End If
End Function
从特定ContentID获取所有后代的查询。如果在此示例中为3,则可以将其更改为另一个值。
SELECT tbContentList.[ContentID], tbContentList.[ParentID], tbContentList.[Item], GetParentIDs([ContentID]) AS Parents
FROM tbContentList
WHERE (((GetParentIDs([ContentID])) Like '*;3;*'));
感谢你的帮助,使我朝着正确的方向前进。