我在关系数据库中有一个表,其中我使用称为Materialized path(也称为Lineage列)的技术对树进行编码 . 也就是说,对于我树中的每个节点,我在表中有一行,并且对于每一行,我有一个名为 ancestry
的字符串列,其中我存储从根节点到该行所表示的节点的路径 .
是否可能,如果是 - 如何,对于 select the rows in the table orderd by preorder ,它们应该按照访问树depth-first的顺序出现在结果集中 . 我使用MySQL - 所以 no recursive queries and no ltree extension .
例如,树,它的表,并按预订顺序排序:
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 回答
我相信你想要的是字母排序 .
我真的不记得MySQL如何连接,但我确信我的意思很明确 .
请注意,它是一个字母排序,所以11将在2之前出现 . 但是,你说你不关心兄弟订购 . 当然,我会将其重写为嵌套集;)
这将按你的“祖先”的最后一个数字排序
我没有尝试使用大于9的数字,你可能需要转换为int