SQL processing Multilevel classification, query results are tree-shaped structure

Source: Internet
Author: User

For multi-level classification of conventional processing methods, many programmers may use the program to read first-level classification records, and then through the first class classification loop read the following sub-classification

The disadvantage of this treatment is: if the amount of data, sub-classification a lot, reached level 4 above, this method of processing the extreme occupation database connection pool

Have a significant impact on performance.

If the CTE under the SQL is processed recursively, the results can be queried at once, and the performance is very good.

Better performance and more convenience for temporary tables than with programs (large data volumes)

With area as (
Select *,id px,cast (id as nvarchar (4000)) px2 from region where parentid=0
UNION ALL
Select A.*,b.px,b.px2+ltrim (a.region_id) from region A joins area B on a.parentid=b.id
) select * from area ORDER by px,px2

Can query the results-all categories and corresponding categories under the classification

ID Title ParentID

1 Guangdong Province 0

2 Guangzhou 1

3 Baiyun District 2

4 Shenzhen 1

5 Hunan Province 0

6 Changsha 5

7 Zhuzhou 5

With area as (
SELECT * from region where parentid=1
UNION ALL
Select A.* from Region A joins area B on a.parentid=b.id
) SELECT * FROM area

Can query the results--Specify classification and corresponding classification under the classification

ID Title ParentID

1 Guangdong Province 0

2 Guangzhou 1

3 Baiyun District 2

Performance Analysis:

For a data table of 3,500 regional records, including provincial, municipal, and county level 3

The query takes 1 seconds, visually feels a little bit slow, but does not affect

Classification with a small amount of data, using absolutely no pressure

SQL processing Multilevel classification, query results are tree-shaped structure

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.