SQL View展平层次结构

时间:2019-07-17 19:19:05

标签: sql

我有一张桌子,上面有一些亲子关系。我想创建一个包含所有可能的位置ID的视图。

我需要sql来完成

Table:

ID  PARENT_ID   LOCATION_ID
1   NULL        ABC
2   1           XYZ
3   NULL        EFG

view results:

LOCATION_ID     ID
XYZ             1
XYZ             2
ABC             1
ABC             2
EFG             3

1 个答案:

答案 0 :(得分:1)

您没有提到您正在使用的数据库,所以我假设使用PostgreSQL。您可以调整针对特定引擎的答案:

with recursive
n as (
  select id, id as grp, location_id from t where parent_id is null
  union all
  select t.id, n.grp, t.location_id
  from n
  join t on t.parent_id = n.id
)
select b.id, a.location_id
from n a
join n b on a.grp = b.grp

结果:

id location_id
-- -----------
1  ABC
2  ABC
1  XYZ
2  XYZ
3  EFG

为了记录,我使用的数据脚本是:

create table t (
  id int,
  parent_id int,
  location_id varchar(10)
);

insert into t (id, parent_id, location_id) values 
  (1, null, 'ABC'),
  (2, 1,    'XYZ'),
  (3, null, 'EFG');  
相关问题