mysql获取记录深度,计算父记录和祖先记录

发布于 2024-09-01 04:27:04 字数 508 浏览 1 评论 0原文

假设我有一个包含字段 post_idparent_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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

明明#如月 2024-09-08 04:27:04

如果您进行大量这样的查询,您可能会发现嵌套集模型比您要查询的邻接列表更合适。 此处对这两种模型进行了很好的讨论。

无论如何,要完成您对邻接列表的要求,您要么在应用程序层中进行递归,要么将级别存储为第三列。

ETA:如果您的级别计数不是很高,您可以使用自连接来实现:

例如具有 2 个祖先的节点:

SELECT t1.node 
FROM mytable AS t1
JOIN mytable AS t2 ON t1.parent = t2.node
JOIN mytable AS t3 ON t2.parent = t3.node
WHERE t3.parent IS NULL;

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:

SELECT t1.node 
FROM mytable AS t1
JOIN mytable AS t2 ON t1.parent = t2.node
JOIN mytable AS t3 ON t2.parent = t3.node
WHERE t3.parent IS NULL;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文