1、樹形結構例子分析:express
以360問答頁面爲例:http://wenda.so.com/c/函數
咱們經過觀察URL,能夠明確該頁面的數據以樹形結構存儲,下面三塊模塊分別爲:學習
①根節點spa
②根節點的第一層子節點3d
③爲左側所選擇節點的下一層子節點code
(圖1)blog
該例簡化的樹形結構圖以下:遞歸
(圖2)字符串
咱們不難發現,每當點擊圖1紅框內的類別時,頁面主體問題部分會顯示該類別節點下全部子節點的問題。所以,須要實現查詢出某節點全部子節點的功能。io
2、表的存儲:
須要存儲兩張表:
一、類別表
create table [QType] ( QID int not null primary key, QPID int not null, QPath varchar(max) not null, QTypeContent varchar(max) not null )
·路徑字段的添加方法:找到父節點的Path +「,」+自身的ID 便可。
二、問題表
create table QContent ( ContentID int not null primary key, TypeID int not null, Content varchar(max) not null )
·問題表的TypeID即爲類別表的QID
3、表的查詢
//查詢出某ID的全部子節點(包含自身) select * from QType where CHARINDEX((select QPath from QType where QID=參數),QPath)>0
CHARINDEX函數說明:CHARINDEX ( expressionToFind , expressionToSearch [ , start_location ] )
經過CHARINDEX若是可以找到對應的字符串,則返回該字符串位置,不然返回0。所以當其>0時表示能在路徑中找到相應字符串,便可查詢到自身以及子節點。
例如:
//查找出以2爲ID節點的全部子節點(包含自身) select * from QType where CHARINDEX((select QPath from QType where QID=2),QPath)>0
查詢結果:
所以,實現以上功能(即點擊類別找到相應問題顯示),則爲:
select QContent.Content from QContent where QContent.TypeID IN (select QType.QID from QType where CHARINDEX((select QType.QPath from QType where QID=參數),QPath)>0)
4、總結
經過新增一個路徑字段的方法,能夠無需使用遞歸,有效提升效率。
正在學習中,歡迎你們指出問題&相互交流!