START WITH and CONNECT BY in Oracle

start with .. connect by clause can be used to select data that has a hierarchical relationship. Usually, it is some sort of parent child relationship like supervisor and an employee.

Let’s assume we have a table called employees. I would like to know employees that directly report to supervisor Id 1122456 –simple, right?

SELECT emplid, supervisor_id
  FROM ps_employees
  WHERE supervisor_id = '1122456';

EMPLID  SUPERVISOR_ID
0119676  1122456
0112356  1122456
0120022  1122456

 

Now I would like to know all employees that report to supervisor Id 1122456 (directly on indirectly).

SELECT     emplid, supervisor_id
      FROM ps_employees
START WITH supervisor_id = '1122456'
CONNECT BY PRIOR emplid = supervisor_id;

EMPLID  SUPERVISOR_ID
0119676  1122456
0112356  1122456
0120022  1122456
0120033  0120022

 

Notice that with the 1st sql we had 3 rows total while using Start With gave us 4 rows back. If you look at the last row on the 2nd select, you notice that employee 0120033 reports to 0120022 who in return reports to 1122456.

 

 

Start with...Connect By子句递归查询一般用于一个表维护树形结构的应用。

创建示例表:

CREATE TABLE TBL_TEST
(
  ID    NUMBER,
  NAME  VARCHAR2(100 BYTE),
  PID   NUMBER                                  DEFAULT 0
);

 

插入测试数据:

INSERT INTO TBL_TEST(ID,NAME,PID) VALUES('1','10','0');
INSERT INTO TBL_TEST(ID,NAME,PID) VALUES('2','11','1');
INSERT INTO TBL_TEST(ID,NAME,PID) VALUES('3','20','0');
INSERT INTO TBL_TEST(ID,NAME,PID) VALUES('4','12','1');
INSERT INTO TBL_TEST(ID,NAME,PID) VALUES('5','121','2');

 

Root往树末梢递归

select * from TBL_TEST
 start with id=1
 connect by prior id = pid

 

从末梢往树ROOT递归

select * from TBL_TEST
 start with id=5
 connect by prior pid = id

 

转载于:https://www.cnblogs.com/GoDevil/archive/2008/08/08/1263846.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值