想知道针对特定ID的所有可能的父子行?

时间:2017-06-01 08:36:50

标签: sql sql-server

如何根据特定ID了解所有可能的父子行?

e.g。有下表:

MyTable的:

-----------------------------------------------------
|   Id    |    PId    |   Description               |
-----------------------------------------------------
|    1    |   NULL    |    A is Parent              |
|    2    |     1     |    B is Child of A          |
|    3    |     2     |    C is Child of B          |
|    4    |   NULL    |    D is Parent              |
|    5    |   NULL    |    E is Parent              |
|    6    |     5     |    F is Child of E          |
-----------------------------------------------------

想要在通过特定身份证明时知道所有可能的父母和孩子

e.g。

CASE-01:

@ MyLookupId = 2 @ MyLookupId = 1 @MyLookupId时= 3 其中一个然后结果应该是,

-------
| Id  |
-------
|  1  |
|  2  |
|  3  |
-------

CASE-02:

@ MyLookupId = 4 然后结果应该是,

-------
| Id  |
-------
|  4  |
-------

CASE-03:

@ MyLookupId = 6 然后结果应该是,

-------
| Id  |
-------
|  5  |
|  6  |
-------
  

这是表格的SQL:

IF OBJECT_ID('tempdb.dbo.#MyTable', 'U') IS NOT NULL DROP TABLE #MyTable; 
SELECT * INTO #MyTable FROM (
    SELECT (1)Id, (NULL)PId, ('A IS Parent')Description UNION ALL
    SELECT (2)Id, (1)PId, ('B IS Child of A')Description UNION ALL
    SELECT (3)Id, (2)PId, ('C IS Child of B')Description UNION ALL
    SELECT (4)Id, (NULL)PId, ('D IS Parent')Description UNION ALL
    SELECT (5)Id, (NULL)PId, ('E IS Parent')Description UNION ALL
    SELECT (6)Id, (5)PId, ('F IS Child of E')Description ) AS tmp

SELECT * FROM #MyTable

2 个答案:

答案 0 :(得分:2)

您可以使用recursive cte

-- temp returns full tree of each rootId (parentid = null)
;WITH temp AS
(
    SELECT sd.Id, sd.PId, sd.Id AS RootId 
    FROM #MyTable sd
    WHERE sd.PId IS NULL

    UNION ALL

    SELECT sd.Id, sd.PId, t.RootId  
    FROM temp t
    INNER JOIN #MyTable sd ON t.Id = sd.PId
)

SELECT t2.Id
FROM temp t
INNER JOIN temp t2 ON t2.RootId = t.RootId
WHERE t.Id = @Id
OPTION (MAXRECURSION 0)

演示链接:http://rextester.com/RAITMT72805

答案 1 :(得分:1)

TriV给出的答案有效,但每次运行查询时都需要计算源表的整个层次结构,这可能在较大规模上表现不佳。

更狭隘的方法是找到仅与您要搜索的<component name="PropertiesComponent"> ... <property name="show.do.not.ask.upgrade.gradle.plugin.version" value="2.2.0" /> ... </component> 相关的父记录和子记录:

ID

输出:

declare @t table(ID int, PID int);
insert into @t values(1,null),(2,1),(3,2),(4,null),(5,null),(6,5);

declare @ID int = 2;

with c as
(
    select ID
            ,PID
    from @t
    where ID = @ID

    union all

    select t.ID
            ,t.PID
    from @t t
        join c
            on(t.PID = c.ID)
)
,p as
(
    select ID
            ,PID
    from @t
    where ID = @ID

    union all

    select t.ID
            ,t.PID
    from @t t
        join p
            on(t.ID = p.PID)
)
select ID
from p

union all

select ID
from c
where c.ID <> @ID
order by ID;