我使用的是Firebird 2.1。有一个表名Folders
,包含以下字段:
- 文件夹ID
- ParentFolderID
- 文件夹名称
如果是根文件夹,则ParentFolderID
为-1,否则它包含父文件夹的ID。
如何查找低级别节点的所有父节点(直到根文件夹(?
我需要递归查询吗?(火鸟支持它们(
类似这样的东西:
WITH RECURSIVE hierarchy (folderid, ParentFolderId, FolderName) as (
SELECT folderid, ParentFolderId, FolderName
FROM folders
WHERE ParentFolderID = -1
UNION ALL
SELECT folderid, ParentFolderId, FolderName
FROM folders f
JOIN hierarchy p ON p.folderID = f.parentFolderID
)
SELECT *
FROM hierarchy
编辑:以下查询将遍历层次结构"向上",查找给定文件夹的所有父级。
WITH RECURSIVE hierarchy (folderid, ParentFolderId, FolderName) as (
SELECT folderid, ParentFolderId, FolderName
FROM folders
WHERE folderid = 42
UNION ALL
SELECT folderid, ParentFolderId, FolderName
FROM folders f
JOIN hierarchy p ON p.parentFolderID = f.folderID
)
SELECT *
FROM hierarchy