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

1

6

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)

Kun answered 5/7, 2011 at 16:6 Comment(2)
@OMG Ponies: Try an English site :) pabloj.blogspot.com/2008/01/new-challenges-new-synthax.htmlOlly
@ypercube: Je ne comprende pas :pSwelling
G
9

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
Gannes answered 5/7, 2011 at 17:23 Comment(4)
I think the query you posted returns all childs of a parent node. Do you have a query that finds all parents of a child node? Thanks.Kun
You just need to "reverse" the starting condition and the "traversal" condition. See my editGannes
Thank you this works! Could you please help with one more thing: I'm using the List command to put the foldernames together in a string (Child 2 / Child 1 / Parent). How can I reverse the result of the query so it will look like: Parent / Child 1 / Child 2?Kun
Check out this posting in the FB mailing list: tech.groups.yahoo.com/group/firebird-support/message/106989Gannes

© 2022 - 2024 — McMap. All rights reserved.