SQL处理多级分类,查询结果呈树形结构
来源:互联网 发布:酷狗铃声截取软件 编辑:程序博客网 时间:2024/05/22 00:54
http://www.jb51.net/article/30991.htm
对于多级分类常规的处理方法,很多程序员可能是用程序先读取一级分类记录,然后通过一级分类循环读取下面的子分类
这样处理的弊端是:如果数据量大,子分类很多,达到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秒,视觉上感觉有点点慢,但不影响
数据量不大的分类,使用绝对无压力
对性能影响很大。
如果用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秒,视觉上感觉有点点慢,但不影响
数据量不大的分类,使用绝对无压力
0 0
- SQL处理多级分类,查询结果呈树形结构
- Oracle SQL树形结构查询
- 多级分类的树形展示
- sql 树形结构查询语句 (sql 2005+)
- 关于SQL Server下无限多级别分类查询解决办法
- 关于SQL Server下无限多级别分类查询解决办法
- 有关树形结构的查询--Sql
- 有关树形结构的查询--Sql
- SQL 中树形结构查询的运用
- 树形结构表记录 :sql递归查询
- 通过oralce的内置函数查询树形结构的结果
- sqlserver实现树形结构递归查询(无限极分类)
- sqlserver实现树形结构递归查询(无限极分类)
- sqlserver实现树形结构递归查询(无限极分类)
- MyBatis 调用MySql存储过程处理树形结构结果集
- Oracle树形结构查询
- 树形结构查询
- ORACLE树形结构查询
- 安装和配置JDK
- WebApp 的 meta 标签
- 杭电ACM 2042:不容易系列之二
- android面试题-简答题(一)
- 串口接收模块 5倍速率采样
- SQL处理多级分类,查询结果呈树形结构
- 软件工程面试题
- 路由协议:学习小结-本机路由与转发路由
- Struts2教程7:上传任意多个文件
- 一步一步跟我学习lucene(2)---lucene的各种Field及其排序
- Infinite recursion (StackOverflowError)解决方案@JsonBackReference
- 2004 TCCC OL1 div1 1000(概率dp,简单)
- 麻辣烫
- 奇怪的排序