简体   繁体   中英

SQL - Database Hierarchy Structure

I have a table with value like this

id | parent | folder_name
-------------------------
1  | 0      | Root
2  | 1      | NSW
3  | 1      | QLD
4  | 2      | Sydney
5  | 3      | Brisbane

from this table i want to get a folder with all parents until higher level. Example: folder_name = Brisbane

id | parent | folder_name
-------------------------
5  | 3      | Brisbane
3  | 1      | QLD
1  | 0      | Root

i want to use JOIN in sql not CTE

Any help would be great

Recursive CTE is what you are looking for

;WITH cte
     AS (SELECT *
         FROM   Yourtable
         WHERE  folder_name = 'Brisbane'
         UNION ALL
         SELECT b.*
         FROM   cte a
                INNER JOIN Yourtable b
                        ON a.parent = b.id)
SELECT *
FROM   cte 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM