mysql获取记录深度,计算父记录和祖先记录
假设我有一个包含字段 post_id
和 parent_post_id
的帖子表。我想返回帖子表中的每条记录以及帖子的“深度”计数。我所说的深度是指存在多少父母和祖先记录。
以这个数据为例...
post_id parent_post_id
------- --------------
1 null
2 1
3 1
4 2
5 4
数据代表这个层次结构...
1
|_ 2
| |_ 4
| |_ 5
|_ 3
查询的结果应该是...
post_id depth
------- -----
1 0
2 1
3 1
4 2
5 3
提前感谢!
Say I have a post table containing the fields post_id
and parent_post_id
. I want to return every record in the post table with a count of the "depth" of the post. By depth, I mean, how many parent and ancestor records exist.
Take this data for example...
post_id parent_post_id
------- --------------
1 null
2 1
3 1
4 2
5 4
The data represents this hierarchy...
1
|_ 2
| |_ 4
| |_ 5
|_ 3
The result of the query should be...
post_id depth
------- -----
1 0
2 1
3 1
4 2
5 3
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您进行大量这样的查询,您可能会发现嵌套集模型比您要查询的邻接列表更合适。 此处对这两种模型进行了很好的讨论。
无论如何,要完成您对邻接列表的要求,您要么在应用程序层中进行递归,要么将级别存储为第三列。
ETA:如果您的级别计数不是很高,您可以使用自连接来实现:
例如具有 2 个祖先的节点:
If you're making a lot of queries like this, you may find that a nested set model is more appropriate than the adjacency list you're asking about. There's a good discussion of both models here.
In any event, to do what you're asking with an adjacency list you're looking at either recursion in the application layer, or storing the level as a 3rd column.
ETA: if your level count isn't terribly high, you can do it with self joins:
e.g. nodes with 2 ancestors: