我的问题是如何标记在返回的行标识符,会告诉我返回row.id是否有更多的孩子递归获取与识别层次结构孩子haschildren
Sample Data
id parenId Name parentName
9 8 nine eight
8 7 eight seven
6 8 six eight
5 8 five eight
4 8 four eight
3 8 three eight
2 1 two one
1 1 one one
12 7 tweleve seven
11 12 eleven twelve
如果我通过的parentId在此查询7低于它返回我
8 7 eight
6 8 six
5 8 five
4 8 four
3 8 three
12 7 tweleve
11 12 eleven
但我要的是有更多的孩子被标记,例如8和12有更多的孩子ID
8 7 eight haschidlren
6 8 six
5 8 five
4 8 four
3 8 three
12 7 tweleve haschidlren
11 12 eleven
WITH name_tree
AS (SELECT Id,
Parentid,
Name,
ParentName
FROM TableWithHiearchy
WHERE Parentid = 7
-- this is the starting point you want in your recursion
UNION ALL
SELECT c.Id,
c.Parentid,
c.Name,
ParentName
FROM TableWithHiearchy c
JOIN name_tree p
ON p.Id = c.ParentId -- this is the recursion
AND c.Id <> c.Parentid
)
SELECT distinct Id, parenId, Name
FROM name_tree
你可以只添加一列CTE像'hasChildren = case(如果存在)(从父表项的表中选择1 id = c.id then 1 else 0 end)'然后在递归CTE的第一部分给出'TableWithHiearchy'别名'c' – ZLK
不确定我是否跟随你的最后一部分“然后在递归CTE的第一部分给TableWithHiearchy别名c“ –
像'WITH name_tree AS(SELECT Id,Parentid,Name,ParentName,hasChildren = case exists when exists(从tablewithhierarchy中选择1,其中parentid = c.id)then 1 else 0 end FROM TableWithHiearchy AS c WHERE Parentid = 7 ' – ZLK