我试图找出如何使用分层表的递归查询。我需要获取给定记录的祖先,并且记录应按层次结构中的级别顺序排序。也就是说,第一个记录应该是顶级节点,下一个应该是子节点,然后是子节点,直到查询的记录。
考虑一个名为" food"以下数据。它是一个简单的层次结构,除了顶级记录之外的每条记录都有一个父记录。
id | parent
-----------+---------
top |
fruit | top
red | fruit
cherry | red
apple | red
orange | fruit
clementine | orange
mandarin | orange
试图理解关于这个主题的各种网页,我拼凑了下面的查询,它给出了普通话"的所有祖先。记录,包括普通话记录本身。
with recursive
child_record(id) as (
values('mandarin')
union
select parent
from food, child_record
where food.id = child_record.id
)
select id from food
where food.id in child_record;
但是,该查询会返回我认为是任意顺序的记录:
fruit
mandarin
orange
top
我希望首先按照最高记录对记录进行排序,然后将级别记录到普通话记录中。
top
fruit
orange
mandarin
如何构建该查询以按照我想要的顺序提供记录?
答案 0 :(得分:2)
我想我已经知道了吗?我犹豫不决,因为我仍然不太了解语法,但以下查询会产生我想要的结果。
with recursive
child_record(level, id) as (
values(0, 'mandarin')
union
select child_record.level+1, food.parent
from food, child_record
where food.id = child_record.id
)
select child_record.level, food.id
from food, child_record
where food.id = child_record.id
order by child_record.level desc;
答案 1 :(得分:0)
我建议按rowid排序:
with recursive
child_record(id) as (
select 'mandarin'
union
select parent
from food, child_record
where food.id = child_record.id
)
select id from food
where food.id in child_record
order by food.rowid;
答案 2 :(得分:0)
通过结合 this answer 和你的,我发现了两个可能的加速(我尚未测量):
from food, child_record
部分)。union all
而不是 union
- 结果已经进行了重复数据删除。此外,我认为这个查询很自然地对其结果进行排序,但我重新添加了 level
字段以确保它。
with recursive ancestor(id, parent, level) as (
select id, parent, 0
from food
where id = 'mandarin' -- this is the starting point you want in your recursion
union all
select f.id, f.parent, a.level + 1
from food f
join ancestor a on a.parent = f.id -- this is the recursion
)
select id
from ancestor
order by level;
┌──────────┐
│ id │
├──────────┤
│ mandarin │
│ orange │
│ fruit │
│ top │
└──────────┘