Oracle Database traversal tree structure table

Source: Internet
Author: User

1. Start from the root node and find the child node

/*
Create table test (id int, pid int, name varchar (10 ));
Insert into test values (1, 0, 'n1 ');
Insert into test values (2, 1, 'n12 ');
Insert into test values (3, 1, 'n13 ');
Insert into test values (4, 2, 'n21 ');
Insert into test values (5, 2, 'n22 ');
Insert into test values (6, 3, 'n31 ');
Insert into test values (7, 3, 'n32 ');
Insert into test values (8, 4, 'n211 ');
Insert into test values (9, 4, 'n212 ');
*/
/*
Find the child node from the root node (you can specify the node level)
*/

Select id, pid, name, level from test
-- Where level = 3
Start with id = 2
Connect by prior id = pid;

 

2. Find the root node from the leaf node

/*
Create Table Test (ID int, PID int, name varchar (10 ));
Insert into test values (1, 0, 'n1 ');
Insert into test values (2, 1, 'n12 ');
Insert into test values (3, 1, 'n13 ');
Insert into test values (4, 2, 'n21 ');
Insert into test values (5, 2, 'n22 ');
Insert into test values (6, 3, 'n31 ');
Insert into test values (7, 3, 'n32 ');
Insert into test values (8, 4, 'n211 ');
Insert into test values (9, 4, 'n212 ');
*/
/*
Find the root node from the leaf node
The prior keyword is put together with whom, who is the target?
The root node's parent node cannot be itself, which will lead to an endless loop
*/

Select * from test/* Where conditions */
Start with ID = 7
Connect by ID = prior PID;

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.