邻接表树 - 如何防止循环引用? [英] Adjacency list tree - how to prevent circular references?

查看:51
本文介绍了邻接表树 - 如何防止循环引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据库中有一个邻接表,用 ID 和 ParentID 来表示树结构:

I have an adjacency list in a database with ID and ParentID to represent a tree structure:

-a
--b
---c
-d
--e

当然,在记录中,ParentID 永远不应该与 ID 相同,但我还必须防止循环引用以防止无限循环.这些循环引用理论上可能涉及 2 个以上的记录.( a->b, b->c, c->a 等)

Of course in a record the ParentID should never be the same as ID, but I also have to prevent circular references to prevent an endless loop. These circular references could in theory involve more than 2 records. ( a->b, b->c, c->a , etc.)

对于每条记录,我将路径存储在这样的字符串列中:

For each record I store the paths in a string column like this :

a    a
b    a/b
c    a/b/c
d    d
e    d/e

我现在的问题是:插入/更新时,有没有办法检查是否会发生循环引用?

My question is now : when inserting/updating, is there a way to check if a circular reference would occur?

我应该补充一点,我对嵌套集模型等都了如指掌.我选择了带有存储路径的邻接方法,因为我发现它更直观.我让它与触发器和一个单独的路径表一起工作,它就像一个魅力,除了可能的循环引用.

推荐答案

如果您像这样存储路径,您可以检查该路径是否不包含 id.

If you're storing the path like that, you could put in a check that the path does not contain the id.

这篇关于邻接表树 - 如何防止循环引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆