有一张emp3表,表结构如下:
create table emp3( id int, mngid int, name nvarchar2(20), primary key(id));
其中mngid是他上级的id号,有了这个谁被谁管一目了然。
然后可以插点值:
insert into emp3(id,mngid,name) values('1',NULL,'Andy'); insert into emp3(id,mngid,name) values('2',1,'Bill'); insert into emp3(id,mngid,name) values('3',1,'Cindy'); insert into emp3(id,mngid,name) values('4',2,'Douglas'); insert into emp3(id,mngid,name) values('5',2,'Edin'); insert into emp3(id,mngid,name) values('6',3,'Felix'); insert into emp3(id,mngid,name) values('7',3,'Green'); insert into emp3(id,mngid,name) values('8',6,'Hitler'); insert into emp3(id,mngid,name) values('9',6,'Idiot'); insert into emp3(id,mngid,name) values('10',8,'Jeep'); insert into emp3(id,mngid,name) values('11',9,'King'); insert into emp3(id,mngid,name) values('12',11,'Linconn');
最后看看层级关系,看看谁看谁的脑袋,谁看谁的屁股。
使用的核心SQL语句是:
select id,level,lpad(' ',(level-1)*3)||name as name from emp3 start with mngid is NULL connect by mngid=prior id;
运行结果:
SQL> select id,level,lpad(' ',(level-1)*3)||name as name 2 from emp3 3 start with mngid is NULL 4 connect by mngid=prior id; ID LEVEL NAME ---------- ---------- ---------------------------------------- 1 1 Andy 2 2 Bill 4 3 Douglas 5 3 Edin 3 2 Cindy 6 3 Felix 8 4 Hitler 10 5 Jeep 9 4 Idiot 11 5 King 12 6 Linconn 7 3 Green 已选择12行。
由上可见,Andy是塔尖,下面是Bill和Cindy,DouglasEdinFelixGreen在第三层,其余的大家自己看。
一棵猴子爬树,其中多少血泪和无奈、以及不为人知的丑闻、甚至不可告人的秘密....
--END--