mysql - 这些 SQL 闭包表示例有什么区别?

标签 mysql recursion tree hierarchical-data transitive-closure-table

我在理解 SQL 闭包表时遇到了一些困难,希望获得一些帮助来理解我找到的一些示例。

假设我有一个名为 sample_items 的表,其中包含以下分层数据:

id   name                   parent_id
1    'Root level item #1'   0
2    'Child of ID 1'        1
3    'Child of ID 2'        2
4    'Root level item #2'   0

树结构实际上应该是这样的:

id
| - 1 
|   | - 2
|       | - 3
| - 4

为了便于查询树(例如查找特定 ID 的所有后代),我有一个名为 sample_items_closure 的表,使用 the method described by Bill Karwin in this excellent SO post .我还使用可选的 path_length 列在需要时查询直接子级或父级。如果我正确理解这个方法,我的闭包表数据将如下所示:

ancestor_id   descendant_id   path_length
1             1               0
2             2               0
1             2               1
3             3               0
2             3               1
1             3               2
4             4               0

sample_items 中的每一行现在在 sample_items_closure 表中都有一个条目,用于自身及其所有祖先。到目前为止,一切都说得通。

然而,在研究其他闭包表示例时,I came across one that adds an additional ancestor for each row链接到根级别 (ancestor_id 0) 并且路径长度为 0。使用我上面的相同数据,这就是闭包表的样子:

ancestor_id   descendant_id   path_length
1             1               0
0             1               0
2             2               0
1             2               1
0             2               0
3             3               0
2             3               1
1             3               2
0             3               0
4             4               0
0             4               0

为了提供更好的上下文,这里是该站点上使用的一个选择查询,已修改以适合我的示例:

SELECT `id`,`parent_id` FROM `sample_items` `items`
  JOIN `sample_items_closure` `closure`
  ON `items`.`id` = `closure`.`descendant_id`
  WHERE `closure`.`ancestor_id` = 2

关于这个方法我有两个问题:

问题 #1:

为什么要添加一个额外的行来将每个后代链接到根级别 (id 0)?

问题 #2:

为什么这些条目的 path_length 为 0,而不是前一个祖先的 path_length+1?例如:

ancestor_id   descendant_id   path_length
1             1               0
0             1               1
2             2               0
1             2               1
0             2               2
3             3               0
2             3               1
1             3               2
0             3               3
4             4               0
0             4               1

奖励问题: 当树的完整结构已经在闭包表中表示时,为什么有些示例仍然包含邻接列表(在我的示例中是 sample_itemsparent_id 列)?

最佳答案

你可以使用 CTE's .它们正是为这些用例而制作的,并且有许多与您的案例很接近的很好的例子。

关于mysql - 这些 SQL 闭包表示例有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28753595/

相关文章:

PHP:如何在数组中填充目录结构

mysql - 无法访问root phpmyadmin

php - 无法连接到 MySQL 数据库

html - 保存自由格式描述以及空格和换行符

Linux 查找子目录中的所有文件并 move 它们

java - 如何在 Boggle 游戏板中递归搜索单词?

C - 使用递归函数将文件夹和子文件夹中的所有 wav 文件路径放入字符串数组中

javascript - 给定一个表示层次结构的数组,在 JS 中将数据输出为树形