How to implement high performance tree view in SQL Server 2005(如何在 SQL Server 2005 中实现高性能的树形视图)
问题描述
构建代表树的表格的最佳方法是什么?我想实现一个可以很好地处理大数据的选择、插入、更新和删除.例如,select 必须支持Expand ALL" - 获取给定节点的所有子节点(以及那里的子节点).
What is the best way to build the table that will represent the tree? I want to implement a select ,insert ,update and delete that will work well with big data. The select for example will have to support "Expand ALL" - getting all the children (and there children) for a given node.
推荐答案
使用 CTE's.
给定树状表结构:
id parent name
1 0 Electronics
2 1 TV
3 1 Hi-Fi
4 2 LCD
5 2 Plasma
6 3 Amplifiers
7 3 Speakers
,这个查询将返回id、parent和深度级别,以树的形式排序:
, this query will return id, parent and depth level, ordered as a tree:
WITH v (id, parent, level) AS
(
SELECT id, parent, 1
FROM table
WHERE parent = 0
UNION ALL
SELECT id, parent, v.level + 1
FROM v
JOIN table t
ON t.parent = v.id
)
SELECT *
FROM v
id parent name
1 0 Electronics
2 1 TV
4 2 LCD
5 2 Plasma
3 1 Hi-Fi
6 3 Amplifiers
7 3 Speakers
将 parent = 0 替换为 parent = @parent 以仅获取树的一个分支.
Replace parent = 0 with parent = @parent to get only a branch of a tree.
如果在 table (parent) 上有一个索引,这个查询将有效地处理一个非常大的表,因为它将递归地使用 INDEX LOOKUP 来查找所有子项每个家长.
Provided there's an index on table (parent), this query will efficiently work on a very large table, since it will recursively use INDEX LOOKUP to find all chilrden for each parent.
要更新某个分支,请发出:
To update a certain branch, issue:
WITH v (id, parent, level) AS
(
SELECT id, parent, 1
FROM table
WHERE parent = 0
UNION ALL
SELECT id, parent, v.level + 1
FROM v
JOIN table t
ON t.parent = v.id
)
UPDATE table t
SET column = newvalue
WHERE t.id IN
(
SELECT id
FROM v
)
其中 @parent 是分支的根.
这篇关于如何在 SQL Server 2005 中实现高性能的树形视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 SQL Server 2005 中实现高性能的树形视图
基础教程推荐
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- oracle区分大小写的原因? 2021-01-01
- 在多列上分布任意行 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
