SQL-传递关系

时间:2018-11-19 20:59:08

标签: sql oracle

假设我有两个表“ Rel”和“ Workers”。 我想将这些名字成对地列出,这些人是和睦的关系。

因此在我的示例中100-> 105和105-> 911表示具有ID 100和911的人 在这种关系中。因此,我希望将其名称列在结果表中。

我尝试使用连接和“连接方式”来解决此问题,但一直失败。希望你们能提供帮助。

enter image description here

1 个答案:

答案 0 :(得分:0)

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE Rel ( Employee, Boss ) AS
SELECT 100, 105 FROM DUAL UNION ALL
SELECT 177, 180 FROM DUAL UNION ALL
SELECT 105, 911 FROM DUAL UNION ALL
SELECT 400, 402 FROM DUAL;

CREATE TABLE Workers ( id, name ) AS
SELECT 100, 'A' FROM DUAL UNION ALL
SELECT 105, 'B' FROM DUAL UNION ALL
SELECT 177, 'C' FROM DUAL UNION ALL
SELECT 180, 'D' FROM DUAL UNION ALL
SELECT 400, 'E' FROM DUAL UNION ALL
SELECT 402, 'F' FROM DUAL UNION ALL
SELECT 911, 'G' FROM DUAL;

查询1

SELECT e.name as employee,
       w.name as related_to
FROM   (
  SELECT CONNECT_BY_ROOT( Employee ) AS employee,
         boss AS related_to
  FROM   Rel
  CONNECT BY PRIOR Boss = Employee
) r
INNER JOIN Workers e
ON e.id = r.employee
INNER JOIN Workers w
ON w.id = r.related_to

Results

| EMPLOYEE | RELATED_TO |
|----------|------------|
|        A |          B |
|        C |          D |
|        E |          F |
|        B |          G |
|        A |          G |