嵌套評論的數據庫表設計


設計嵌套評論數據庫表可仿效無限級分類,在表中加一個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 UserComments as 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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM