从使用物化路径编码树的表中选择,按深度优先排序(无递归/ ltree)

时间:2012-02-01 14:03:55

标签: mysql sql tree relational-database hierarchy

我在关系数据库中有一个表,我使用称为Materialized path的技术(也称为Lineage列)对树进行编码。也就是说,对于我树中的每个节点,我在表中有一行,并且对于每一行,我有一个名为ancestry的字符串列,其中我存储从根节点到此行所代表的节点的路径。 / p>

是否可能,如果是 - 如何,选择按顺序排序的表中的行,它们应该按照访问树的顺序出现在结果集中depth-first。我使用MySQL - 所以没有递归查询,没有ltree扩展

例如,树,它的表,并按预订顺序排序:

 1        SELECT * FROM nodes   SELECT * FROM nodes ORDER BY ?depth_first_visit_order?
| \       id | ancestry         id | ancestry
2   3     -------------         -------------
|  | \    1  | NULL             1  | NULL           NOTE: I don't care about the
4  5  6   2  | 1                2  | 1                    order of siblings!
   |      3  | 1                4  | 1/2
   7      4  | 1/2              3  | 1
          5  | 1/3              5  | 1/3
          6  | 1/3              7  | 1/3/5
          7  | 1/3/5            6  | 1/3

注意:我对通过物化路径编码明确感兴趣!
相关:What are the options for storing hierarchical data in a relational database?

2 个答案:

答案 0 :(得分:1)

我相信你想要的是字母排序。

SELECT id, ancestry, ancestry + '/' + CAST(id as nvarchar(10)) AS PathEnumeration
FROM nodes
ORDER BY 3 ASC;

我真的不记得MySQL如何连接,但我确定我的意思很清楚。

1
1/2
1/2/4
1/3
1/3/5
1/3/5/7
1/3/6

请注意,这是一个字母排序,所以11将在2之前出现。但是,你说你不关心兄弟订购。当然,我会将其重写为嵌套集;)

答案 1 :(得分:0)

这将按你的“祖先”的最后一个数字排序

select *, 
Substring(ancestry,LEN(ancestry) - Charindex('/',Reverse(ancestry))+2, LEN(ancestry)) as END_CHAR
from nodes
order by END_CHAR desc

我没有尝试使用大于9的数字,你可能需要转换为int