H2 데이터베이스 귀속 구문

2792 단어 데이터베이스
--  
create table module (
        sid number(10) not null, 
        module_name varchar2(20) not null, 
        pid number(10)
);
--  
insert into module(sid, module_name, pid) values (1, ' 1', null);
insert into module(sid, module_name, pid) values (2, ' 2', null);
insert into module(sid, module_name, pid) values (3, ' 3', null);
insert into module(sid, module_name, pid) values (4, ' 21', 2);
insert into module(sid, module_name, pid) values (5, ' 31', 3);
insert into module(sid, module_name, pid) values (6, ' 211', 4);
insert into module(sid, module_name, pid) values (7, ' 11', 1);
insert into module(sid, module_name, pid) values (8, ' 111', 7);
insert into module(sid, pid, module_name) values(9, 3,  ' 32');
--  
with tree(sid, pid, name) as (
        select m.sid, m.pid, m.module_name from module m where m.pid is null
        union all
        select m2.sid, m2.pid, m2.module_name 
                from tree inner join module m2 on tree.sid = m2.pid
) select * from tree order by sid;
--  
with tree(sid, pid, name) as (
        select m.sid, m.pid, m.module_name from module m where m.sid = 2
        union all
        select m2.sid, m2.pid, m2.module_name 
                from tree inner join module m2 on tree.sid = m2.pid
) select * from tree order by sid;

--  , distinct
with tree(sid, pid, name) as (
        select m.sid, m.pid, m.module_name from module m where m.sid in (5,6,8, 9)
        union all
        select distinct  m2.sid, m2.pid, m2.module_name 
                from tree inner join module m2 on tree.pid = m2.sid
) select * from tree order by sid;
--  , 
with tree(sid, pid, name, level) as (
        select m.sid, m.pid, m.module_name, 0 from module m where m.pid is null
        union all
        select m2.sid, m2.pid, m2.module_name, tree.level + 1 
                from tree inner join module m2 on tree.sid = m2.pid
) select * from tree where level = 1 order by sid;
--  with as... select , 
with tree(sid, pid, name) as (
        select m.sid, m.pid, m.module_name from module m where m.sid = 2
        union all
        select m2.sid, m2.pid, m2.module_name 
                from tree inner join module m2 on tree.sid = m2.pid
) delete from module where sid in (select sid from tree);

좋은 웹페이지 즐겨찾기