嵌套评论的数据库表设计

来源:互联网 发布:tensorflow 保存模型 编辑:程序博客网 时间:2024/06/08 06:27

设计嵌套评论数据库表可仿效无限级分类,在表中加一个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
)

 

数据库表中添加如下数据:

1
以上,Thread字段以"/"分隔,罗列了所有的父级Id,Depth字段显示的是层级。

 

查询所有的评论:

  select SPACE(u.Depth*6) + u.Content as 评论 from UserCommentsas u

2

 

如果希望结合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))

3

0 0