ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [postgreSQL] with recursive 예제
    db 2021. 3. 29. 23:19

    Oracle과는 다르게 PostgreSQL은 union all과 함께 작동됩니다.

     

    예제 테이블 생성과 데이터 삽입

    create table recursive_test(group_id numeric, parent_id numeric);
    
    insert into recursive_test values(0, null);
    insert into recursive_test values(1, 0);
    insert into recursive_test values(2, 1);
    insert into recursive_test values(3, 1);
    insert into recursive_test values(4, 1);
    insert into recursive_test values(5, 2);
    insert into recursive_test values(6, 2);
    insert into recursive_test values(7, 2);
    insert into recursive_test values(8, 5);
    insert into recursive_test values(9, 5);
    insert into recursive_test values(10, 3);
    insert into recursive_test values(11, 3);
    insert into recursive_test values(12, 3);
    insert into recursive_test values(13, 9);
    insert into recursive_test values(14, 9);

     

    문법

    with recursive Alias_VIEW([그룹컬럼],[부모컬럼]) as (
    	select 그룹컬럼, 부모컬럼
    	from 그룹테이블
    	where 그룹컬럼시작조건
    	
    	union all
    	
    	select 그룹컬럼, 부모컬럼
    	from 그룹테이블, Alias_VIEW
    	where 그룹번호 = 부모 번호 < 역순 >
    ) select 그룹컬럼, 부모컬럼 from Alias_VIEW;
    

     

     

    부모 조회

     

    with recursive childlist(group_id,parent_id, level) as (
    		select group_id, parent_id, 0	
    		from recursive_test rt
    		where group_id = '13'
    		union all 
    		select c.group_id,c.parent_id, p.level+1 
    		from recursive_test c, childlist p
    		where c.group_id = p.parent_id
    	) select *from childlist;
    

     

    13의 부모인 9,

    9 의 부모인 5,

    5 의 부모인 2,

    2 의 부모인 1,

    1 의 부모인 0

     

    9 5 2 1 0 조회

     

    자식 조회

     

    with recursive childlist(group_id,parent_id, level) as (
    	select group_id, parent_id, 0	
    	from recursive_test rt
    	where group_id = '5'
    	union all 
    	select c.group_id,c.parent_id, p.level+1 
    	from recursive_test c, childlist p
    	where c.parent_id = p.group_id
    ) select *from childlist;

     

    5 의 자신의 5,

    5 의 자식인 8,

    5 의 자식인 9,

    9 의 자식인 13,

    9 의 자식인 14

     

    5 8 9 13 14 조회

     

    댓글

Designed by Tistory.