SQL和树中的链接列表


8

尽管SQL与表之类的操作更相关,而与递归无关,但说我们想实现链接(或双链接)列表概念(例如我们在C语言中)。
考虑到我们可以使项目从链接列表中的任何位置移动到任何位置,有什么方法可以有效地做到这一点?
一些使用CLR的解决方案?
还是它真的不应该带到SQL Server?

请注意,这个问题也演变成VS链表的讨论

尽管我固定了SQL Server,但这是一个类似学术的问题,因此,即使我们仅得出结论,那就是永远不要将其带入数据库,也可以采用其他解决方案。

Answers:


10

链表只是一个非常简单的有向无环图。没有理由为什么这很难解决,或者对于SQL Server应该避免。

考虑一下,树结构比链表更复杂。Internet上将数据存储在关系数据库中的论坛的每种实现都实现了链接列表的基础。在此页面上,答案形成一个链接列表。可以添加和删除它们。他们可以移动位置(又名,按投票排名)。

要使用的特定表示形式仅取决于您希望在维护列表(插入,更新,删除)和检索之间进行权衡。

--Works great for INS/UPD/DEL, In order retrieval isn't the best.
CREATE TABLE Item (id int identity, next int, prev int) 

--makes in order retrieval fast, deletes are a problem, inserts may require re-numbering.    
CREATE TABLE Item (id int identity, position  int ) 

--Works great for in-order retrieval, and allow cheap insertion/deletion, 
--certain edge cases might be tricky to handle.
CREATE TABLE (id int identity, position Decimal(24,12 )  ) 
--for inserts, use the average of the before and after, for deletes, just delete.

更新:问题是关于SQL Server中的树与链表

SQL Server具有HierarchyId数据类型,该数据类型旨在简化树状结构的实现和查询。

CREATE TABLE Item (id int identity, NodeId HierarchyId)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.