Oracle通过找到他的直接父母和他的兄弟姐妹

时间:2014-03-23 17:54:12

标签: sql oracle siblings

Id          DepId
100         0
110         100
115         110
120         100
130         100
150         110
160         110
165         110
200         195
210         110
220         0
230         110
240         0
310         110

根据这些数据,我需要按Id查询,并获得直接父母及其所有兄弟姐妹的结果

例如,如果我搜索ID 115,我应该检索该人的父记录110及其兄弟姐妹的行,例如:120,{ {1}}。

110         100
120         100
130         100

如何使用oracle connect by?

获得此结果

答案:

130

1 个答案:

答案 0 :(得分:0)

您似乎按错误的顺序连接了值。 ORDER在逐行连接中很重要。

但我也会重写。

With RULES (ID, DepID) AS (

SELECT 100,         0 from dual union all
SELECT 110,         100 from dual union all
SELECT 115,         110 from dual union all
SELECT 120,         100 from dual union all
SELECT 130,         100 from dual union all
SELECT 150,         110 from dual union all
SELECT 160,         110 from dual union all
SELECT 165,         110 from dual union all
SELECT 200,         195 from dual union all
SELECT 210,         110 from dual union all
SELECT 220,         0 from dual union all
SELECT 230,         110 from dual union all
SELECT 240,         0 from dual union all
SELECT 310,         110 from dual )

SELECT * 
FROM RULES 
where DEPID in (
    SELECT id 
    FROM RULES
    WHERE LEVEL = 3
    Start with ID in (115)
    CONNECT BY PRIOR depid = id)

如果你总是回到一定数量的水平,那么我认为只是让连接更容易理解/维护

SELECT R3.* 
FROM RULES R1 
INNER JOIN RULES R2 
  on R1.DepID = R2.ID 
INNER JOIN RULES R3 
  on R2.DepID = R3.DepID 
WHERE R1.ID = 115