Oracle的sql:
select t.org_id,
t.org_name,
t.org_level,
connect_by_root(org_id) org_up_id,
connect_by_root(org_name) org_up_name,
connect_by_root(org_level) org_level,
connect_by_isleaf leaf
from dm_org t
connect by prior t.org_id=decode(t.org_up_id , t.org_id , 0 , t.org_up_id);
请教各位大神,此段sql用PostgreSQL如何写?
根据题目的描述,假设表dm_org,有四个字段:
decode(t.org_up_id , t.org_id , 0 , t.org_up_id)
,推测根节点的org_up_id等于org_id。假设表中包含以下六行记录:
org_id | org_up_id | org_level | org_name |
---|---|---|---|
1 | 1 | 1 | 'A' |
2 | 1 | 2 | 'B' |
3 | 1 | 2 | 'C' |
4 | 2 | 3 | 'D' |
5 | 3 | 3 | 'E' |
6 | 5 | 4 | 'F' |
利用题主的SQL查询结果如下:
org_id | org_name | org_level | org_up_id | org_up_name | org_level | leaf |
---|---|---|---|---|---|---|
1 | A | 1 | 1 | A | 1 | 0 |
2 | B | 2 | 1 | A | 1 | 0 |
4 | D | 3 | 1 | A | 1 | 1 |
3 | C | 2 | 1 | A | 1 | 0 |
5 | E | 3 | 1 | A | 1 | 0 |
6 | F | 4 | 1 | A | 1 | 1 |
2 | B | 2 | 2 | B | 2 | 0 |
4 | D | 3 | 2 | B | 2 | 1 |
3 | C | 2 | 3 | C | 2 | 0 |
5 | E | 3 | 3 | C | 2 | 0 |
6 | F | 4 | 3 | C | 2 | 1 |
4 | D | 3 | 4 | D | 3 | 1 |
5 | E | 3 | 5 | E | 3 | 0 |
6 | F | 4 | 5 | E | 3 | 1 |
6 | F | 4 | 6 | F | 4 | 1 |
因为没有指定start with
语句,从功能上来说,是递归查询dm_org表所有记录的子节点。与之对应的PostgreSQL的查询语句是:
with recursive leafs as (
select
distinct
parents.org_id as leaf_id
from
dm_org as parents
left join
dm_org as children
on
parents.org_id = children.org_up_id
where
children.org_id is null
), trees as (
select
org_id,
org_name,
org_level,
org_id as org_up_id,
org_name as org_up_name,
org_level as org_up_level
from
dm_org
union all
select
dm_org.org_id,
dm_org.org_name,
dm_org.org_level,
trees.org_up_id,
trees.org_up_name,
trees.org_up_level
from
dm_org
inner join
trees
on
dm_org.org_up_id = trees.org_id
and dm_org.org_id != trees.org_id
)
select
trees.*,
leafs.leaf_id is not null as leaf
from
trees
left join
leafs
on
trees.org_id = leafs.leaf_id
order by
org_up_id,
org_id;
定义了两个公共表表达式,其中:
connect_by_isleaf
这样的关键字。版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。