最近一个朋友接手了一个项目,为自己部门开发文档版本管理系统。我在和他闲聊中,听他说起数据表设计时遇到的一个疑惑。听他说完后感觉这样的问题还是有一些普遍性的,在这里进行一下分享。
问题描述
文档版本管理最主要的是要维护文档的版本链。这很容易让人想到链表这种数据结构,所以我的那位朋友很快就给出了如下的表结构:
create table Table_Docunment
(
Docunment_Id int not null identity(1000, 1) primary key,
Docunment_Name nvarchar(64) not null,
Docunment_SubmitDate datetime not null,
Docunment_PreId int not null default(-1),
Docunment_NxtId int not null default(-1),
.......
);
其中Docunment_PreId存放前一版本文档的Id,Docunment_NxtId存放下一版本文档的Id。
起初还没有感觉出什么问题,但当他试图向Table_Docunment填充测试数据或试图写一个存储过程来获取其链上最新的文档时,感觉非常痛苦。
在他的存储过程中需要进行循环,他自己知道这样性能不好,但又不清楚如何解决。
解决方案
问题的关键在于初始的设计并不适合系统的使用场景。原始的设计导致了取某文档的下一版本或上一版本都需要进行连接(Join)操作,若要获得最新版本文档,还需要进行循环。
对原始设计进行修改,新的表结构如下(省略了部分字段):
create table Table_Docunment
(
Docunment_Id int not null identity(1000, 1) primary key,
Docunment_Name nvarchar(64) not null,
Docunment_ChainId int not null default(-1),
Docunment_VersionId int not null default(-1),
Docunment_SubmitDate datetime not null,
......
);
其中Docunment_ChainId为当前文档所属的版本链,Docunment_VersionId为当前文档在版本链中的版本号(从1开始的连续编号)。
<