Recursive query tree structure __oracle in Oracle tables

Source: Internet
Author: User

If you store a tree structure in a table, you need to deposit two field IDs and ParentID in the tables, indicating who the parent of each record is.

Table:treetable

Id ParentID Field 3 ......
1 Null A ......
2 1 B ......
3 2 D ......

Select ... can be used in Oracle. From ... Start with (starting node) ... CONNECT by ... PRIOR (indicates previous record) ... (Order siblings by levels) clause implements a recursive query tree structure.

1. Traverse the child node from the root node.: (A whole tree)

SELECT * from treetable start and id=1 connect by prior Id=parentid (prior represents previous record)

2. Traced from one leaf to the root node: (one branch of the tree)

SELECT * from treetable start and id=3 connect by prior Parentid=id (prior represents previous record)

3. The level keyword can be queried.

Select *,level from treetable start and id=1 connect by prior Id=parentid (prior represents the previous record)



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.