微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

这样处理的弊端是:如果数据量大,子分类很多,达到4级以上,这方法处理极端占用数据库连接池
性能影响很大。 如果用sql下面的CTE递归处理的话,一次性就能把结果给查询出来,而且性能很不错
比用程序处理(数据量很大的情况),临时表性能更好,更方便
<div class="codetitle"><a style="CURSOR: pointer" data="27270" class="copybut" id="copybut27270" onclick="doCopy('code27270')"> 代码如下:

<div class="codebody" id="code27270">
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
<div class="codetitle"><a style="CURSOR: pointer" data="18984" class="copybut" id="copybut18984" onclick="doCopy('code18984')"> 代码如下:
<div class="codebody" id="code18984">
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秒,视觉上感觉有点点慢,但不影响
数据量不大的分类,使用绝对无压力

原文地址:https://www.jb51.cc/mssql/63749.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐