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 可以很好地检索树结构
基础教程推荐
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 无法解决整理冲突 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
