SQL to retrieve tree structure nicely(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 可以很好地检索树结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQL 可以很好地检索树结构
基础教程推荐
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 带更新的 sqlite CTE 2022-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
