作用
connect by主要用於父子,祖孫,上下級等層級關系的查詢
語法
{ CONNECT BY [ NOCYCLE ] condition [AND condition]... [ START WITH condition ]
| START WITH condition CONNECT BY [ NOCYCLE ] condition [AND condition]...}
解釋:
start with: 指定起始節點的條件
connect by: 指定父子行的條件關系
prior: 查詢父行的限定符,格式: prior column1 = column2 or column1 = prior column2 and ... ,
nocycle: 若數據表中存在循環行,那么不添加此關鍵字會報錯,添加關鍵字后,便不會報錯,但循環的兩行只會顯示其中的第一條
循環行: 該行只有一個子行,而且子行又是該行的祖先行
connect_by_iscycle: 前置條件:在使用了nocycle之后才能使用此關鍵字,用於表示是否是循環行,0表示否,1 表示是
connect_by_isleaf: 是否是葉子節點,0表示否,1 表示是
level: level偽列,表示層級,值越小層級越高,level=1為層級最高節點
例子
自定義數據
1 -- 創建表 2 create table employee( 3 emp_id number(18), 4 lead_id number(18), 5 emp_name varchar2(200), 6 salary number(10,2), 7 dept_no varchar2(8) 8 ); 9 10 -- 添加數據 11 insert into employee values('1',0,'king','1000000.00','001'); 12 insert into employee values('2',1,'jack','50500.00','002'); 13 insert into employee values('3',1,'arise','60000.00','003'); 14 insert into employee values('4',2,'scott','30000.00','002'); 15 insert into employee values('5',2,'tiger','25000.00','002'); 16 insert into employee values('6',3,'wudde','23000.00','003'); 17 insert into employee values('7',3,'joker','21000.00','003');commit;
查詢以emp_id為0開始的節點的所有直屬節點
1 select emp_id,lead_id,emp_name,prior emp_name as lead_name,salary 2 from employee 3 start with lead_id=0 4 connect by prior emp_id = lead_id 5 6 -- 等同於 7 select emp_id,lead_id,emp_name,prior emp_name as lead_name,salary 8 from employee 9 start with emp_id=1 10 connect by prior emp_id = lead_id
查詢以emp_id為6開始的節點
1 select emp_id,lead_id,emp_name,salary 2 from employee 3 start with emp_id=6 4 connect by prior lead_id=emp_id;
level偽列的使用,格式化層級
1 select lpad(' ',level*2,' ')||emp_name as name,emp_id,lead_id,salary,level 2 from employee 3 start with lead_id=0 4 connect by prior emp_id=lead_id
connect_by_root 查找根節點
1 select connect_by_root emp_name,emp_name,lead_id,salary 2 from employee 3 where dept_no='002' 4 start with lead_id=1 5 connect by prior emp_id = lead_id;
標注循環行
1 -- 插入一條數據,與另一條emp_id=7的數據組成循環行 2 insert into employee 3 values('3',7,'joker_cycle','21000.00','003'); 4 commit; 5 -- connect_by_iscycle("CYCLE"), connect by nocycle 6 select emp_id,emp_name,lead_id,salary,connect_by_iscycle as cycle 7 from employee 8 start with lead_id=0 9 connect by nocycle prior emp_id = lead_id;
connect_by_isleaf 是否是葉子節點
1 select emp_id,emp_name,lead_id,salary,connect_by_isleaf 2 from employee 3 start with lead_id=0 4 connect by nocycle prior emp_id=lead_id;