Tree query and connect by in Oracle

Source: Internet
Author: User
  • Tree query and connect by in Oracle

    Using connect by and start with to create a report similar to a tree is not difficult, as long as you follow the following basic principles:

    When using connect by, the order of each clause should be:
    Select
    From
    Where
    Start
    Connect
    Order

  • Prior orders the report from the root to the leaf (if the prior column is a parent) or from the leaf to the root (if the prior column is a descendant ).
  • The where clause can exclude individuals from the tree, but does not exclude their descendants (or the ancestor, if the prior column is a descendant ).
  • The conditions in connect by (especially not equal to) Eliminate the individual and all its children (or the ancestor, depending on how to track the tree ).
  • Connect by cannot be used together with tables in the where clause.

The following are examples:


1. Traverse from root to leaf
SELECT n_parendid, n_name, (LEVEL-1), n_id
FROM navigation
WHERE n_parendid IS NOT NULL
Start with n_id = 0
Connect by n_parendid = PRIOR n_id;

2. Traverse from leaf to root
SELECT n_parendid, n_name, (LEVEL-1), n_id
FROM navigation
WHERE n_parendid IS NOT NULL
Start with n_id = 300
Connect by n_id = PRIOR n_parendid;

3. exclude individuals, but not their children
SELECT n_parendid, n_name, (LEVEL-1), n_id
FROM navigation
WHERE n_parendid is not null and n_id! = 2
Start with n_id = 0
Connect by n_parendid = PRIOR n_id;

4. remove an individual and all its children
SELECT n_parendid, n_name, (LEVEL-1), n_id
FROM navigation
WHERE n_parendid IS NOT NULL
Start with n_id = 0
Connect by n_parendid = PRIOR n_id AND n_id! = 2;

5. Change the display Sequence
SELECT n_parendid, n_name, (LEVEL-1), n_id
FROM navigation
WHERE n_parendid IS NOT NULL
Start with n_id = 0
Connect by n_parendid = PRIOR n_id
Order by n_viewnum DESC;

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.