SQL處理多級分類,查詢結果呈樹形結構
發(fā)布日期:2022-01-14 11:31 | 文章來源:腳本之家
對性能影響很大。 如果用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 白云區(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
可以查詢出結果—-指定分類及相應分類下子分類
id title parentid
1 廣東省 0
2 廣州 1
3 白云區(qū) 2
性能分析:
對于一個3500條地區(qū)記錄的數據表,其中有省,市,縣3級
查詢用時要1秒,視覺上感覺有點點慢,但不影響
數據量不大的分類,使用絕對無壓力
版權聲明:本站文章來源標注為YINGSOO的內容版權均為本站所有,歡迎引用、轉載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網站,禁止在非maisonbaluchon.cn所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內容來源于網友推薦、互聯網收集整理而來,僅供學習參考,不代表本站立場,如有內容涉嫌侵權,請聯系alex-e#qq.com處理。
相關文章
關注官方微信