Sample Code for tree-like Query of Oracle Database

Source: Internet
Author: User

Oracle DatabaseOfTree QueryIs what we will introduce in this article, including the basic syntax of tree query, the construction environment,Root NodeTraversalSubnodeAnd trace the child nodes to the root node. Let's take a look at this part.

Basic Syntax:

 
 
  1. select...from tabename start with cond1 connect by  prior cond2 where cond2 

Note:

Cond1 is a limit statement for the root node.

Cond2 is the connection condition, where prior indicates the previous record, indicating that the father of the record is the previous record.

Cond3 is a filter condition.

Build Environment:

 
 
  1. create table Family(  
  2. id integer,  
  3. parentid integer,  
  4. name varchar2(50)  
  5. )  
  6. insert into family values(0,0,'a')  
  7. insert into family values(1,0,'b')  
  8. insert into family values(2,1,'c')  
  9. insert into family values(3,1,'d')  
  10. insert into family values(4,1,'e')  
  11. insert into family values(5,1,'f') 

Traverse sub-nodes through the root node

For example, query the information of all the children whose father is equal to 1.

 
 
  1. select * from family start with parentid=1 connect by prior id=parentid 

Tracing to the root node through the sub-node

For example:

 
 
  1. select * from family start with id=5 connect by prior parentid=id 

Note: If the ORA-01436 is reported: The coonect by loop in the user database, the parentid In the first data is changed to null, otherwise the loop find parentid will not find it!

Extended: query the level by level keyword

Select t. *, level from family t start with parentid = 1 connect by prior id = parentid

Note:The table must use an alias.

Here is an introduction to the tree-like Query of Oracle databases. If you want to learn more about Oracle databases, please read the article http://database.51cto.com/oracle/, which will surely help you reap the benefits!

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.