我有一个表有3列的人:Id,Name,ParentId,其中ParentId是父行的Id.
目前,要显示整个树,它必须遍历所有子元素,直到不再有子元素为止.它看起来效率不高.
解决方法
假设您的亲子关系水平有限,我认为设计没有任何问题.以下是使用递归CTE检索关系的快速示例:
USE tempdb; GO CREATE TABLE dbo.tree ( ID INT PRIMARY KEY,name VARCHAR(32),ParentID INT FOREIGN KEY REFERENCES dbo.tree(ID) ); INSERT dbo.tree SELECT 1,'grandpa',NULL UNION ALL SELECT 2,'dad',1 UNION ALL SELECT 3,'me',2 UNION ALL SELECT 4,'mom',1 UNION ALL SELECT 5,'grandma',NULL; ;WITH x AS ( -- anchor: SELECT ID,name,ParentID,[level] = 0 FROM dbo.tree WHERE ParentID IS NULL UNION ALL -- recursive: SELECT t.ID,t.name,t.ParentID,[level] = x.[level] + 1 FROM x INNER JOIN dbo.tree AS t ON t.ParentID = x.ID ) SELECT ID,[level] FROM x ORDER BY [level] OPTION (MAXRECURSION 32); GO
别忘了清理:
DROP TABLE dbo.tree;
This might be a useful article.另一种选择是hierarchyid
,但我发现它对于大多数情况来说过于复杂.