SQL很好地检索树结构 [英] SQL to retrieve tree structure nicely
问题描述
给出简单的数据结构:
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屋!