在 sql server 2005 中设置层次结构的最佳方法是什么?
我正在尝试为公司建立一个层次结构。我使用的是 SQL Server 2008 并使用层次结构 id 来设置它。但现在我需要回到 SQL Server 2005...并且“就这样做”...无论如何,我想到了以这种简单的方式设置它 -
Id | ParentId | CompanyName | Desc
其中 ParentId
是一个 int 字段,它将存储父级的 id。我猜根的 ParentId
将为零。有没有更好的方法来设置层次结构?
我真的对层次结构没有那么复杂的要求...我想知道什么会让我猜想更容易地遍历层次结构并更有效地使用它。
I am trying to setup an hierarchial structure for company. I was using SQL Server 2008 and used hierarchy id to set it up. But now I need to move back to SQL Server 2005...and "just do it"... Anyways I thought of setting it up this simple way -
Id | ParentId | CompanyName | Desc
where ParentId
is a int field which will store id of the parent. I guess the root will have its ParentId
as zero. Are there better ways to setup the hierarchy structure?
I really don't have that complex requirements for hierarchy... I want to know just what would make I guess traversing though the hierarchy easier and working with it more efficient.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
“简单的方法”很好,并且与 CTE(公共表表达式)配合得很好。然而,正如 Kev 所建议的,还有其他方法各有利弊。
因此,最终这取决于您的具体要求,以及对数据执行多少插入查询和分层查询,因为不同方法的性能在这方面可能有很大差异。
The "simple way" is fine and works well with CTEs (Common Table Expression). However, as suggested by Kev, there are other ways which have their pros and cons.
So in the end it depends on your exact requirements, and how much insert vs. hierarchical queries will be done on the data because the performance of the different approaches can vary a lot in this regard.
Joe Celko 使用嵌套集的方法,其中表有一个“左”和“右”列,指的是层次结构,这就是我通常看到的方法
Joe Celko 可能会比我更好地解释它
嵌套集
Joe Celko's method of using nested sets where your table has a "left" and "right" column referring to the hierarchy is how I have usually seen it done
Joe Celko will probably explain it better than I can
Nested sets
不幸的是,据我所知,您的设置方式是正确的。您现在无法轻松遍历链接,因为您丢失了 GetAncestor 和 GetDescendant。一个不错的替代方案是使用 CTE 来替代 GetAncestor 和 GetDescendant,并递归地使用它们。
这是一个示例(使用菜单层次结构):
本文应该有所帮助(示例来自此处):
http://www.infoq.com/news/2007/10/CTE
Unfortunately, as far as I know the way you are setting it up is the correct way. You can't traverse the links as easily now because you lose GetAncestor and GetDescendant. A decent replacement is to use CTEs to replace GetAncestor and GetDescendant, and use them recursively.
Here is an example (using a menu hierarchy):
This article should help (example is from here):
http://www.infoq.com/news/2007/10/CTE