Getting hierarchy data from self-referencing tables

前端 未结 5 1554
孤独总比滥情好
孤独总比滥情好 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:38

    Oracle has a very convenient syntax for retrieving hierarchical data like this:

    select
        item_id,
        item_parent,
        level as depth
    from
        items
    connect by
        prior item_id = item_parent
    start with
        item_parent not in (select item_id from items)
    

    This starts with the root nodes of your trees as those items whose item_parent does not exist in the table as item_id, and selects all children of those nodes, along with their depth in the tree.

提交回复
热议问题