我有一张像这样的价值表
id | parent | folder_name
-------------------------
1 | 0 | Root
2 | 1 | NSW
3 | 1 | QLD
4 | 2 | Sydney
5 | 3 | Brisbane
从这张表中我想得到一个包含所有父母的文件夹,直到更高级别。示例:folder_name = Brisbane
id | parent | folder_name
-------------------------
5 | 3 | Brisbane
3 | 1 | QLD
1 | 0 | Root
我想在sql而不是JOIN
CTE
任何帮助都会很棒
答案 0 :(得分:1)
Recursive CTE
正是您要找的
;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