Adn*_*nan 11 sql sql-server hierarchy transitive-closure-table
我有一个数据库,其中包含使用邻接列表模型存储的类别层次结构.
层次结构深度为3级(不包括假想的根节点),包含大约1700个节点.第二级和第三级的节点可以有多个父节点.另外一个表用于多对多关系,如下所示:
CREATE TABLE dbo.Category(
id int IDENTITY(1,1) NOT NULL,
name varchar(255) NOT NULL,
)
CREATE TABLE dbo.CategoryHierarchy(
relId int IDENTITY(1,1) NOT NULL,
catId int NOT NULL,
parentId int NOT NULL,
)
Run Code Online (Sandbox Code Playgroud)
如果我转向使用传递闭包表方法(为了数据完整性等)是否有一个相对容易的查询,我可以执行,将生成闭包表的值?(使用SQL Server 2005)
我查看文章和演示文稿,例如Bill Karwin的分层数据模型,但只有单个节点的插入查询,我需要永远创建这样的树.
谢谢.
编辑:
CategoryHierarchy表中的RelID纯粹是为了主键,它与Category表的节点ID无关.
还有闭包表,我的意思是这样一个表:
CREATE TABLE ClosureTable (
ancestor int NOT NULL,
descendant int NOT NULL,
[length] int NOT NULL,
)
Run Code Online (Sandbox Code Playgroud)
前两列是复合主键,并且是Category.id的单独外键.
Ale*_*rra 16
我试图弄清楚同样的事情,但希望它在一个递归的CTE中.这不会对你有用(SQL Server 2008+),但这是我最终为其他任何人寻找的东西.
有点难以解释它是如何工作的,但关键是锚点不是你的根节点(在哪里parent_id IS NULL),而是所有你在关闭表中的零深度行.
CREATE TABLE dbo.category
(
id INT IDENTITY(1, 1) NOT NULL,
parent_id INT NULL
)
Run Code Online (Sandbox Code Playgroud)
INSERT INTO dbo.category (id, parent_id)
VALUES
(1, NULL),
(2, 1),
(3, 1),
(4, 2)
Run Code Online (Sandbox Code Playgroud)
WITH category_cte AS
(
SELECT
id AS ancestor,
id AS descendant,
0 AS depth
FROM dbo.category
UNION ALL
SELECT
CTE.ancestor AS ancestor,
C.id AS descendant,
CTE.depth + 1 AS depth
FROM dbo.category AS C
JOIN category_cte AS CTE
ON C.parent_id = CTE.descendant
)
SELECT * FROM category_cte
Run Code Online (Sandbox Code Playgroud)
ancestor descendant depth
-------- ---------- -----
1 1 0
2 2 0
3 3 0
4 4 0
2 4 1
1 2 1
1 3 1
1 4 2
Run Code Online (Sandbox Code Playgroud)
我认为自己已经能够解决问题。
如果有人有更好的方法,请发表评论。
IF OBJECT_ID('dbo.ClosureTable', 'U') IS NOT NULL
DROP TABLE dbo.ClosureTable
GO
CREATE TABLE dbo.ClosureTable (
ancestor int NOT NULL,
descendant int NOT NULL,
distance int NULL
)
GO
DECLARE @depth INT
SET @depth = 1
INSERT INTO dbo.ClosureTable (ancestor, descendant, distance)
SELECT catid, catid, 0 FROM dbo.Category -- insert all the self-referencing nodes
WHILE (@depth < 4) -- my tree is only 4 levels deep, i.e 0 - 3
BEGIN
INSERT INTO dbo.ClosureTable (ancestor, descendant, distance)
SELECT ct.ancestor, h.catid, @depth
FROM dbo.ClosureTable ct INNER JOIN dbo.CategoryHierarchy h ON ct.descendant = h.parentid
WHERE ct.distance = @depth - 1
SET @depth = @depth + 1
END
Run Code Online (Sandbox Code Playgroud)
干杯:)