SQL处理多级分类,查询结果呈树形结构

对于多级分类常规的处理方法,很多程序员可能是用程序先读取一级分类记录,然后通过一级分类循环读取下面的子分类

这样处理的弊端是:如果数据量大,子分类很多,达到4级以上,这方法处理极端占用数据库连接池

对性能影响很大。

 

如果用SQL下面的CTE递归处理的话,一次性就能把结果给查询出来,而且性能很不错

比用程序处理(数据量很大的情况),临时表性能更好,更方便

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 join area b on a.parentid=b.id
)select  * from area order by px,px2

 

可以查询出结果—-所有分类及相应分类下子分类

id     title                    parentid

1      广东省                0

2         广州                 1

3            白云区           2

4        深圳                  1

5     湖南省                  0

6        长沙                  5

7        株洲                  5

 

with area as(
select * from region where parentid=1
union all
select a.*  from region a join area b on a.parentid=b.id
)select  * from area

 

可以查询出结果—-指定分类及相应分类下子分类

id     title                    parentid

1      广东省                0

2         广州                 1

3            白云区           2

 

 

性能分析:

对于一个3500条地区记录的数据表,其中有省,市,县3级

查询用时要1秒,视觉上感觉有点点慢,但不影响

数据量不大的分类,使用绝对无压力

posted on 2012-08-01 09:18  口明明口  阅读(7466)  评论(1编辑  收藏  举报

导航