【问题标题】:Selecting all parents in the order of relation from hierarchical table SQL从分层表SQL中按关系顺序选择所有父级
【发布时间】:2013-08-30 15:37:53
【问题描述】:

我有一个这样的表,在同一个表中有父子关系

帐号|家长 ID |帐户名称 ---------------------------------------------- 1 | 0 |根 2 | 1 |孩子1 3 | 1 |孩子2 4 | 2 |孩子3 5 | 4 |孩子1 6 | 5 |孩子1 7 | 6 |孩子1 8 | 6 |孩子1

因此,当我发送帐户 ID 7 时,我必须按照孩子、父亲、祖父等顺序获取表格。这样。所以对于 7,我需要获取所有 parets这个

帐户ID --------- 7 6 5 4 2 1

所以最重要的一点是顺序。它应该是从底层到下一个更高然后到下一个......

【问题讨论】:

标签: sql sql-server sql-server-2008


【解决方案1】:

您可以使用recursive CTE

declare @childAccID int
set @childAccID = 7  

;WITH Rec_CTE 
    AS(
        SELECT 1 AS Level, 
               tChild.*
        FROM dbo.TableName tChild
        WHERE tChild.AccountID = @childAccID

        UNION ALL

        SELECT Level + 1 AS Level, 
               parent.*
        FROM Rec_CTE tParent
        INNER JOIN  dbo.TableName parent 
          ON parent.AccountID = tParent.ParentID
    )
SELECT * FROM Rec_CTE
ORDER BY Level

DEMO

【讨论】:

【解决方案2】:

试试这个:

create table DemoTable
(
    accountid bigint
    ,parentid bigint
    ,accountname nvarchar(128)
)
insert DemoTable(accountid,parentid,accountname)
select 1, null, 'Root'
union select 2, 1, 'Child1'
union select 3, 1, 'Child2'
union select 4, 1, 'Child3'
union select 5, 2, 'Child1.1'
union select 6, 2, 'Child1.2'
go
declare @findMe bigint = 6;
with myCTE as
(
    select accountid,parentid,accountname,1 hierarchyLevel
    from DemoTable
    where accountid = @findMe

    union all

    select b.accountid,b.parentid,b.accountname, a.hierarchyLevel + 1
    from myCTE a
    inner join DemoTable b
    on b.accountid = a.parentid
)
select * from myCTE
order by hierarchyLevel

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    • 1970-01-01
    • 2020-09-25
    相关资源
    最近更新 更多