まず、テストデータを設定しましょう...
CREATE TABLE EMPLOYEE (
EMPLOYEE_ID INT PRIMARY KEY,
MANAGER_ID INT,
NAME VARCHAR2(20),
TITLE VARCHAR2(20),
FOREIGN KEY (MANAGER_ID) REFERENCES EMPLOYEE (EMPLOYEE_ID)
);
INSERT INTO EMPLOYEE(EMPLOYEE_ID, NAME, TITLE) VALUES (1, 'Rob', 'CEO');
INSERT INTO EMPLOYEE VALUES (2, 1, 'Bob', 'Manager');
INSERT INTO EMPLOYEE VALUES (3, 2, 'Matilda', 'Secretary');
INSERT INTO EMPLOYEE VALUES (4, 1, 'Steve', 'Manager');
INSERT INTO EMPLOYEE VALUES (5, 4, 'John', 'Senior Worker');
INSERT INTO EMPLOYEE VALUES (6, 5, 'Paul', 'Junior Worker');
INSERT INTO EMPLOYEE VALUES (7, 4, 'Anny', 'Senior Worker');
次のクエリは、Steveと彼のすべての部下を再帰的に返します。
SELECT *
FROM EMPLOYEE
START WITH EMPLOYEE_ID = 4
CONNECT BY PRIOR EMPLOYEE_ID = MANAGER_ID;
EMPLOYEE_ID MANAGER_ID NAME TITLE
------------------ ------------------ -------------------- --------------------
4 1 Steve Manager
5 4 John Senior Worker
6 5 Paul Junior Worker
7 4 Anny Senior Worker
「反転」すると、PRIOR
代わりにSteveの上司が表示されます。
SELECT *
FROM EMPLOYEE
START WITH EMPLOYEE_ID = 4
CONNECT BY EMPLOYEE_ID = PRIOR MANAGER_ID;
EMPLOYEE_ID MANAGER_ID NAME TITLE
------------------ ------------------ -------------------- --------------------
4 1 Steve Manager
1 Rob CEO