我的数据库中有以下数据:
Parent Child
====== =====
1 2
1 3
2 4
2 5
3 6
5 7
我想要检索这棵树的所有子孙。我可以将它与WITH递归一起使用吗?
输出应为:
Parent Child
====== =====
1 2
1 3
1 4
1 5
1 7
2 4
2 5
2 7
3 6
5 7
感谢。
答案 0 :(得分:1)
WITH cte AS (
SELECT parent, child, 1 AS depth
FROM MyTable
UNION ALL
SELECT t1.parent, t2.child, depth+1
FROM cte t1
INNER JOIN @t t2 ON (t2.parent = t1.child)
WHERE depth < 2
)
SELECT parent, child
FROM cte