先创建一个树形结构的表t_test
create table T_TEST ( ID NUMBER, PID NUMBER, TITLE VARCHAR2(30) ) tablespace TEST pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K minextents 1 maxextents unlimited ); insert into T_TEST (ID, PID, TITLE) values (1, 0, '一一'); insert into T_TEST (ID, PID, TITLE) values (2, 0, '二二'); insert into T_TEST (ID, PID, TITLE) values (3, 1, '一三'); insert into T_TEST (ID, PID, TITLE) values (4, 1, '一四'); insert into T_TEST (ID, PID, TITLE) values (5, 3, '一三五'); insert into T_TEST (ID, PID, TITLE) values (6, 3, '一三六'); insert into T_TEST (ID, PID, TITLE) values (7, 2, '二七'); insert into T_TEST (ID, PID, TITLE) values (8, 2, '二八'); insert into T_TEST (ID, PID, TITLE) values (9, 7, '二七九'); insert into T_TEST (ID, PID, TITLE) values (10, 7, '二七十'); commit;
sys_connect_by_path 函数主要作用是可以把一个父节点下的所有子节点通过某个字符进行区分,然后连接在一个列中显示
--子id=父id 倒树型结构
--父id=子id 正树型结构
先看子id=父id 倒树型结构例子:
select level ,id,pid,title,sys_connect_by_path( title , '/' ) as path from t_test --where level=3 start with id= 1 connect by prior id = pid order by pid;
显示结果:
再看父id=子id 正树型结构 例子:
select level ,id,pid,title,sys_connect_by_path( title , '/' ) as path from t_test --where level=3 start with pid= 3 connect by prior pid = id order by pid;
结果显示: