create database NestedCommnets
use NestedCommnets
Create 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,返回字符串的小数位数
select
SPACE(u.Depth*6) + u.Content as 评论,
u.Thread + LTRIM(STR(u.Depth,100,0)) as 排序
from UserComments as u
order by u.Thread + LTRIM(STR(u.Depth,100,0))

转自:嵌套评论的数据库表设计