示例:
| id | name | parent_id | floor |
|----------------------------------------|
| 1 | boss1 | null | green |
| 2 | emp1 | 1 | null |
| 3 | boss2 | null | blue |
| 4 | emp3 | 3 | null |
| 5 | emp4 | 2 | null |
现在,我想回答一个问题,哪个员工在绿色地板上工作(明显的答案:boss1,emp1和emp4)?我知道编程很容易,但是我只想使用SQL(Postgres)来做。
谢谢!
答案 0 :(得分:1)
您需要recursive common table expression才能穿过树。您还需要将非空值从父级“携带”到子级,以模拟值的继承。
with recursive tree as (
select id, name, parent_id, floor
from employees
where parent_id is null
union all
select c.id, c.name, c.parent_id, coalesce(c.floor, p.floor) as floor
from employees c
join tree p on p.id = c.parent_id
)
select *
from tree;
给出示例数据,以上结果将返回:
id | name | parent_id | floor
---+-------+-----------+------
1 | boss1 | | green
3 | boss2 | | blue
2 | emp1 | 1 | green
4 | emp3 | 3 | blue
5 | emp4 | 2 | green
现在,可以通过将WHERE
条件添加到最终选择中来更改为返回绿色底行的所有行。
with recursive tree as (
... as above ...
)
select *
from tree
where floor = 'green';