Getting hierarchy data from self-referencing tables

前端 未结 5 1572
孤独总比滥情好
孤独总比滥情好 2020-12-13 15:00

Let\'s say you have the following table:

items(item_id, item_parent)  

... and it is a self-referencing table - item_parent r

5条回答
  •  甜味超标
    2020-12-13 15:55

    If the database is SQL 2005 / 2008 then...

    The easiest way to get this is using a CTE (Common Table Expression) that is designed to recurse.

     WITH myCTE (Item_id, Depth)
     AS
     (
        Select Item_ID, 0 as Depth From yourTable where Item_Parent=0
        Union ALL
        Select yourTable.Item_ID, Depth + 1 
        From yourTable 
        inner join myCte on yourTable.item_Parent = myCte.Item_Id
     )
    
     Select Item_id, Depth from myCTE
    

    The output is as follows:

    Item_Id  Depth
        1   0
        2   0
        3   1
        4   1
        5   2
    

    From that you can format it as you wish.

提交回复
热议问题