我遇到这么多麻烦,任何帮助都会很棒。
我在Oracle 10中有一个简单的表,看起来像这样
Name | EmployeeID | ManagerID | Title
我需要一个查询来返回给定员工ID的所有报告
因此,如果我将员工ID传递给1000,它将循环直接报告,然后是间接报告等。
我弄乱了递归样本,但似乎没有一个对我有效。我知道我只是没有正确设置它。谢谢你的帮助。
FYI。我正在寻找一个SQL查询。
答案 0 :(得分:2)
这样的事情应该有效:
select lpad(' ', 2*(level-1)) || name as employeename
from employee_table
start with employeeid = 1000
connect by prior employeeid = managerid;
lpad()函数用于缩进结果,以便您可以查看谁向谁报告。
如果您不希望在结果中包含employeeid 1000,只需更改:
start with employeeid = 1000
为:
start with managerid = 1000
答案 1 :(得分:2)
首先,让我们设置测试数据......
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
给了我们史蒂夫的上司:
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