SQL處理多級分類,查詢結(jié)果呈樹形結(jié)構(gòu)
更新時間:2012年08月03日 17:23:37 作者:
對于多級分類常規(guī)的處理方法,很多程序員可能是用程序先讀取一級分類記錄,然后通過一級分類循環(huán)讀取下面的子分類
這樣處理的弊端是:如果數(shù)據(jù)量大,子分類很多,達到4級以上,這方法處理極端占用數(shù)據(jù)庫連接池
對性能影響很大。
如果用SQL下面的CTE遞歸處理的話,一次性就能把結(jié)果給查詢出來,而且性能很不錯
比用程序處理(數(shù)據(jù)量很大的情況),臨時表性能更好,更方便
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
可以查詢出結(jié)果—-所有分類及相應分類下子分類
id title parentid
1 廣東省 0
2 廣州 1
3 白云區(qū) 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
可以查詢出結(jié)果—-指定分類及相應分類下子分類
id title parentid
1 廣東省 0
2 廣州 1
3 白云區(qū) 2
性能分析:
對于一個3500條地區(qū)記錄的數(shù)據(jù)表,其中有省,市,縣3級
查詢用時要1秒,視覺上感覺有點點慢,但不影響
數(shù)據(jù)量不大的分類,使用絕對無壓力
對性能影響很大。
如果用SQL下面的CTE遞歸處理的話,一次性就能把結(jié)果給查詢出來,而且性能很不錯
比用程序處理(數(shù)據(jù)量很大的情況),臨時表性能更好,更方便
復制代碼 代碼如下:
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
可以查詢出結(jié)果—-所有分類及相應分類下子分類
id title parentid
1 廣東省 0
2 廣州 1
3 白云區(qū) 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
可以查詢出結(jié)果—-指定分類及相應分類下子分類
id title parentid
1 廣東省 0
2 廣州 1
3 白云區(qū) 2
性能分析:
對于一個3500條地區(qū)記錄的數(shù)據(jù)表,其中有省,市,縣3級
查詢用時要1秒,視覺上感覺有點點慢,但不影響
數(shù)據(jù)量不大的分類,使用絕對無壓力
相關(guān)文章
一次SQL調(diào)優(yōu)數(shù)據(jù)庫性能問題后的過程(300W)
對單表超過300w+數(shù)據(jù)的Web應用程序進行測試后發(fā)現(xiàn)了一些功能、性能問題,采取了以下辦法來進行調(diào)整2010-03-03在SQL Server中使用ISNULL執(zhí)行空值判斷查詢
這篇文章主要介紹了在SQL Server中使用ISNULL執(zhí)行空值判斷查詢,ISNULL的好處是可以直接寫在SELECT查詢語句中,需要的朋友可以參考下2014-08-08distinct 多列問題結(jié)合group by的解決方法
distinct 多列問題 group by 解決2010-06-06設(shè)定sql server定期自動備份數(shù)據(jù)庫
設(shè)定sql server定期自動備份數(shù)據(jù)庫...2007-01-01