SQL 可以很好地检索树结构 [英] SQL to retrieve tree structure nicely

查看:31
本文介绍了SQL 可以很好地检索树结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于简单的数据结构:

ID    |    Category_Name    |    Parent_ID

示例:

1          Cars                    0
2          Boxes                   0
3          Lamborghinis            1
4          VW Camper Vans          1
5          Big Boxes               2
6          Small Boxes             2
7          Cereal Boxes            2
8          Broken Lambos           3
9          Yellow Ones             3
10         Rusty                   8
11         Milkshake Stained       8
12         Chocolate Flavour       11
13         Strawberry              11
14         Indiscernible Solution  11

表示一个简单的树导航结构,以编程方式以可呈现的格式检索树的最佳方法是什么?我们可以创建一个 SQL 语句来按顺序"检索它们吗?

Representing a simple tree navigation structure, what would programatically be the best way to retrieve the tree in a presentable format? Can we create an SQL statement to retrieve them 'in order'?

感谢您的帮助!如果我的方法有误,也欢迎评论.

Thanks for any help! If my approach is wrong, feel free to comment also.

我使用的是 SQL-Server 2000.

I'm using SQL-Server 2000.

推荐答案

如果您使用的是 SQL Server 2008,您可能想尝试一下新的 hierarchyid 数据类型.

If you're using SQL Server 2008 you might want to try out the new hierarchyid data type.

如果您不是,那么另一种方法是查看 嵌套集 模型适用于所有数据库.

If you're not then another way is to look into the nested sets model which works on all databases.

如果您使用的是 SQL Server 2005 及更高版本,则可以使用 递归 CTE 检索树结构.

If you're using SQL Server 2005 and up you can use recursive CTEs to retreive the tree structure.

这篇关于SQL 可以很好地检索树结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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