設計嵌套評論數據庫表可仿效無限級分類,在表中加一個ParentId字段。嵌套評論頁面大致這樣:
評論1
回復評論1
恢復評論1
評論2
回復評論2
評論3
......
但是, 在顯示評論的時候,如果使用ParentId會涉及到多表的聯結,嵌套層級越多意味着表之間的聯結增多,這樣會影響查詢效率。
於是,我們想到在表中增加一個字段,用來顯示所有的層級:/1/2/5/
設計數據庫和表:
create database NestedCommnetsuse NestedCommnetsCreate table UserComments(Id int not null identity(1, 1),ParentId int not null,Content nvarchar(100) not null,Depth smallint not null,Thread nvarchar(max) not null)
往數據庫表中添加如下數據:

以上,Thread字段以"/"分隔,羅列了所有的父級Id,Depth字段顯示的是層級。
查詢所有的評論:
select SPACE(u.Depth*6) + u.Content as 評論 from UserComments as u
如果希望結合Thread和Depth字段進行排序:
--STR(nExpression [, nLength [, nDecimalPlaces]])返回與指定表達式對應的字符串--nLength,返回的字符串長度;nDecimalPlaces,返回字符串的小數位數selectSPACE(u.Depth*6) + u.Content as 評論,u.Thread + LTRIM(STR(u.Depth,100,0)) as 排序from UserComments as uorder by u.Thread + LTRIM(STR(u.Depth,100,0))


