计算 MySQL 中父子模型的深度
MySQL下父子模型如何计算节点深度?
我需要深度,除其他外,在我的列表中创建缩进(用 PHP 编码)。
How do I calculate a node's depth in a parent-child model under MySQL?
I'll need the depth to, among other things, create the indent in my list (coded with PHP).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这可能是一个老问题,但我只是想让其他人知道我几个月前找到了解决方案。 我最近确实在这里写过:http://en。 someotherdeveloper.com/articles/adjacency-list-model-with-深度-calculation/
This might be an old question, but I just want to let others know that I found a solution some months ago. I did recently write about it here: http://en.someotherdeveloper.com/articles/adjacency-list-model-with-depth-calculation/
如果你只想复制粘贴,这里是我的例子。
我有包含 ID 和 PARENT_ID 字段的表项目。
If you want just to copy paste here is my example.
I have table Projects with ID and PARENT_ID fileds.
这取决于数据库中层次结构的实际实现。 如果您使用嵌套集模型(http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/)您可以通过单个选择检索完整的父子路径。
更新:好的,由于您要使用邻接列表模型,我建议在表中存储节点级别。 它不仅会在一个查询中为您提供节点深度,而且还允许您在一个查询中检索到该节点的完整路径(尽管该查询必须动态生成):
因为您知道您的节点处于开启状态N 级不需要左连接,并且在 id /parent_id 上给出适当的索引,这应该相当快。
这种方法的缺点是,您必须在节点移动期间保持节点级别更新,但这应该相当简单和快速,因为您只会对节点本身及其子节点执行此操作 - 而不是对表的大部分进行操作,如你会用嵌套集来做。
That depends on the actual implementation of your hierarchy in the database. If you are using nested sets model (http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/) you can retrieve the full parent-to-child path via a single select.
Update: Ok, since you're going with adjacency list model I suggest to store node level in the table. Not only will it give you the node depth in one query, but it will also allow you to retrieve the entire path to that node in one query (albeit that query would have to be dynamically generated):
Since you know that your node is on level N there's no need for left joins and, given appropriate indexes on id / parent_id this should be reasonably fast.
The downside to this approach is that you'll have to keep node level updated during node moves, but that should be reasonably straightforward and fast as you would only do it for the node itself and its children - not for the majority of the table as you would do with nested sets.