to_root.md 1.3 KB
Newer Older
M
Mars Liu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
# 树结构溯根

现有一个表 node

```postgresql
create table node
(
    id      serial primary key,
    pid     integer,
    content text
);
```

其 pid 列引用 id 列,形成一个树结构,根节点的 pid 为 0。

现在我们希望写一个查询,找到某一个给定id的记录,其父节点、父节点的父节点,直至根节点的路径。那么这个查询应该是:

## 答案

```postgresql
M
format  
Mars Liu 已提交
21 22 23 24 25 26 27 28
with recursive t(id, pid, content) as (
    select id, pid, content
    from node
    where id = $1
    union all
    select node.id, node.pid, node.level
    from node
             join t on node.id = t.pid)
M
Mars Liu 已提交
29 30 31 32 33 34 35 36 37 38
select node.id, node.pid, content
from node
         join t on node.id = t.id;
```

## 选项

### 没有递归定义

```postgresql
M
format  
Mars Liu 已提交
39 40 41 42 43 44 45 46
with t as (
    select id, pid, content
    from node
    where id = $1
    union all
    select node.id, node.pid, node.level
    from node
             join t on node.id = t.pid)
M
Mars Liu 已提交
47 48 49 50 51 52 53 54 55 56 57
select node.id, node.pid, content
from node
         join t on node.id = t.id;
```

### 平凡的连接查询无法处理递归问题

```postgresql
select node.id, node.pid, node.content
from node
         join node as p on node.pid = p.id
M
format  
Mars Liu 已提交
58
where id = $1;
M
Mars Liu 已提交
59 60 61 62 63 64 65
```

### 子查询无法处理递归问题

```postgresql
select node.id, node.pid, node content
from node as t
M
format  
Mars Liu 已提交
66
where t.pid = (select id from t where id = t.pid)
M
Mars Liu 已提交
67
```