欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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ù)量不大的分類,使用絕對無壓力

相關(guān)文章

最新評論