我在这方面遇到了很多麻烦,任何帮助都会很棒。
我在 Oracle 10 中有一个简单的表,看起来像这样
Name | EmployeeID | ManagerID | Title
我需要一个查询来返回给定员工 ID 的所有报告
因此,如果我将员工 ID 传递给 1000,它将遍历直接报告,然后是间接报告等。
我弄乱了递归样本,但似乎没有一个对我有用。我知道我只是没有正确设置它。谢谢你的帮助。
供参考。我正在寻找关于此的 SQL 查询。
首先,让我们设置测试数据...
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
像这样的东西应该工作:
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