(摘自:http://blog.youkuaiyun.com/figo645/article/details/47975493)
设计嵌套评论数据库表可仿效无限级分类,在表中加一个ParentId字段。嵌套评论页面大致这样:
评论1
回复评论1
恢复评论1
评论2
回复评论2
评论3
......
但是,在显示评论的时候,如果使用ParentId会涉及到多表的联结,嵌套层级越多意味着表之间的联结增多,这样会影响查询效率。
于是,我们想到在表中增加一个字段,用来显示所有的层级:/1/2/5/
设计数据库和表:
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
(注:space()是SQL的函数: 返回一个字符串,其中包含N个空格字符。)
如果希望结合Thread和Depth字段进行排序:
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))
(注:
STR(nExpression [, nLength [, nDecimalPlaces]])函数:返回与指定表达式对应的字符串;
nLength函数:返回的字符串长度;
nDecimalPlaces函数:返回字符串的小数位数
)