限制数据库树深度
通常,当我表示父子层次结构时,我有一个如下表(我还可能添加其他深度列以加快速度),其中父级和子级都是与同一实体表中的行的外键关系。
实体关系
复合密钥
孩子ID
父 id
我想弄清楚的是如何将树的深度限制为一。换句话说,如果某人是孩子的父母,我如何防止该父母本身就是孩子,从而不可能有祖父母甚至更进一步?
Typically when I represent a parent child hierarchy I have a table as follows (I might also add additional depth columns to speed things up), where parents and children are both foreign key relationships to rows from the same entity table.
Entity Relationships
composite pkey
child id
parent id
What I am trying to figure out is how to limit the depth of the tree to one. In other words, if somebody is the parent of a child, how to I prevent that parent from being a child in itself, so it is impossible to have grandparents or even further?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据您的 RDBMS,您可以在 INSERT/UPDATE 触发器中处理类似的事情。对于简单地限制父母不能同时成为孩子来说,这应该不会太糟糕(尽管我讨厌使用不必要的触发器)。如果您尝试将级别限制为一定数量(例如 100),那么您可能会开始遇到性能问题。
在 MS SQL Server 中,您还可以在约束中使用用户定义的函数。但是有限制,所以我不知道它在这里是否有效。不过我会尝试测试一下。
编辑:
我刚刚在 MS SQL Server 2008 上测试了这个,看起来它工作正常:
Depending on your RDBMS, you can handle something like this in an INSERT/UPDATE trigger. For simply restricting a parent to not also be a child it shouldn't be too bad (although I hate using triggers any more than necessary). If you were trying to limit to a certain number of levels (say 100) then you might start to run into performance issues.
In MS SQL Server you can also use user-defined functions in constraints. There are limits however, so I don't know if it would work here. I'll try to test it though.
EDIT:
I just tested this on MS SQL Server 2008 and it looks like it works correctly: