您的位置:首页 > 数据库

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

2012-08-03 17:23 393 查看
这样处理的弊端是:如果数据量大,子分类很多,达到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秒,视觉上感觉有点点慢,但不影响
数据量不大的分类,使用绝对无压力

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  多级分类