How can you detect a parent with a nested relationship in a database using SQL?

蓝咒 提交于 2019-12-22 05:10:28

问题


I'm using Firebird 2.1. There is a table name Folders, with the fields:

  • FolderID
  • ParentFolderID
  • FolderName

ParentFolderID is -1 if it's the root folder -- otherwise it contains the parent folder's ID.

How can I find all parents (up to the root folder) of a low level node?

Do I need a recursive query? (Firebird supports them)


回答1:


Something like this:

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

Edit: the following query will walk the hierarchy "up", finding all parents of a given folder.

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


来源:https://stackoverflow.com/questions/6585631/how-can-you-detect-a-parent-with-a-nested-relationship-in-a-database-using-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!