下面是我统计的几种方案:
第一种方案(递归式):
简单的表结构为:
CategoryID int(4),
CategoryName nvarchar(50),
ParentID int(4),
Depth int(4)
这样根据ParentID一级级的运用递归找他的上级目录。
还有可以为了方便添加CategoryLeft,CategoryRight保存他的上级目录或下级目录
第二种方案:
设置一个varchar类型的CategoryPath字段来保存目录的完整路径,将父目录id用符号分隔开来。比如:1,5,8,10
第三种方案:
每级分类递增两位数字的方法 示例:
一级分类:01,02,03,04...
二级分类:0101,0102,0103,0104...
三级分类:010101,010102,010103... 分析一下,其实第三种方案并不能真正意义上做无限级的分类,而第二种方案,虽然比较容易得到各上级及下级的分类信息。但,添加和转移分类的时候操作将很麻烦。
而且,也完全违反了数据库设计范式。 其实我也一直在用第二种方案的。为了查找方便,我有时都在新闻表里加上CategoryID和CategoryPath 而我今天要说的算法其实是第二种方案的改进版,一般做分类都是使用一个表格来保存分类信息。
而我这里,要新建两个表格,一个表格是保存分类信息表,一个保存分类关系表。 表结构如下:
表1:tomi_Category
CategoryID int(4),'编号
CategoryName nvarchar(50),'分类名称
Depth int(4),'深度
表2:tomi_CategoryBind
CategoryID int(4),
BindCategoryID int(4),
Depth int(4),添加,编辑,删除操作有点麻烦。。我是直接用存储过程的。。不知道大家能看得懂不。。哈哈。
1、添加分类(Category_Add)
<div class="codetitle"><a style="CURSOR: pointer" data="72622" class="copybut" id="copybut72622" onclick="doCopy('code72622')"> 代码如下: