使用递归遍历树结构 [英] Traversing a tree structure using recursion

查看:200
本文介绍了使用递归遍历树结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理数据库上的一个表。列是:id,name,parent_id,hasChildren。 (parent_id将是表中的一个id,如果parent_id为null,那么记录是父母)



什么是最好的方式循环访问此数据,以便我可以将其添加到如下列表:



- item1

- item2

>>项目2.1

>>>>项目2.1.1

>>项目2.2

- item3





编辑 - 当我说列表时,我的意思就像一个列表框



edit2 - woops,是的,列表需要按照父记录按字母顺序排序。我正在使用mssql。

解决方案

SQL Server 2008允许您在表中定义层次结构:





您还可以使用递归CTE:




I am dealing with one table on the database. The columns are: id, name, parent_id, hasChildren. (parent_id would be an id on the table. if parent_id is null, the record is a parent.)

What would be the best way to loop through this data so I can add it to a list like:

- item1
- item2
>> item 2.1
>>>> item 2.1.1
>> item 2.2
- item3

etc etc.

edit - when i say "list" i mean like a listbox

edit2 - woops, yes, list needs to be sorted by parent record alphabetically. i'm using mssql.

解决方案

SQL Server 2008 allows you to define hierarchies in a table:

You could also use a recursive CTE:

这篇关于使用递归遍历树结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆