[转载]关于商城系统中商品类别的设计(续篇)

上一节我说数据库设计有一块硬伤,到底在哪儿?先看下图:

看上图中有什么地方是相同的?

“品牌”→“三星”在手机数码分类里面有,在电脑办公分类里面也有,这有什么问题?再来看看上篇中的那个关系图:

再看数据库中存储的数据,首先是(T_FilterCategory表)

如下(T_FilterAttributes表)

如下(T_FilterCategory与T_FilterAttributes之间的关联表)

如上图,既然“品牌”→“三星”在手机数码分类里面有,在电脑办公分类里面也有,那么如果只是像上面这个关联表这么保存筛选条件和筛选条件值,我如何区分哪个是手机数码下的“品牌”→“三星”,哪个是电脑办公分类下的“品牌”→“三星”?如果我不区分它,会发生什么情况?现在有这么个业务,需要我通过用户选择的三级类别,展示出指定三级类型下的“筛选条件”和对应的“筛选条件值”,那么我该怎么实现呢,按照上面的关系图,假设用户点击了“手机数码分类”下的“手机”,它的类别编号为“14”,那么我可以写出如下SQL语句:

第一步,根据用户选择的类别获取其下的“筛选条件”。

select fc.fc_Id,fc.fc_Name from T_FilterCategory as fc
	inner join RF_Columns_FilterCategory as cfc on fc.fc_Id = cfc.fc_Id
	inner join T_Columns as col on cfc.col_Id = col.col_Id
where col.col_Id = '14'

  执行结果如下:

现在我再根据上面的“筛选条件”获取对应的“筛选属性值”:

select fa.attr_Id,fa.attr_Name from T_FilterAttributes as fa
     inner join RF_FilterCategory_TFilterAttributes as fcfa on fa.attr_Id = fcfa.attr_Id
     inner join T_FilterCategory as fc on fcfa.fc_Id = fc.fc_Id
where fc.fc_Id in
	(select fc.fc_Id from T_FilterCategory as fc
		inner join RF_Columns_FilterCategory as cfc on fc.fc_Id = cfc.fc_Id
		inner join T_Columns as col on cfc.col_Id = col.col_Id
	where col.col_Id = '14')

  结果如下:

看上面红色方框中的“筛选属性值”,像宏碁、华硕、戴尔、Gateway、清华同方等,它们是电脑厂商,而不是手机厂商,然而却出现在手机类别下,这不是有问题吗?

所以这种设计有问题,因为它缺了一张表!这张表就是存储关联表RF_FilterCategory_TFilterAttributes与T_Columns表之间的关系的中间表。为什么要加中间表?因为一个三级类别可以对应多个RF_FilterCategory_TFilterAttributes,而一个RF_FilterCategory_TFilterAttributes又可以被多个三级类别拥有。图示见:顶部 图(1)

于是我继续加表,名曰:RF_Columns_FilterCategory_FilterAttributes,如下图:

然后建立外键关联,如下图:

然后完整的关系图如下:

然后我再次执行上面那个业务,假设用户选择的三级类别的编号为14,我需要获取其下的所以“筛选条件值“,那么SQL语句如下:

with t as
    (
        select FA.attr_Id,FA.attr_Name,CDF.col_Id,CDF.sort from T_FilterAttributes as FA
            inner join dbo.RF_FilterCategory_TFilterAttributes as DF on FA.attr_Id = DF.attr_Id
            inner join dbo.RF_Columns_FilterCategory_FilterAttributes as CDF on CDF.df_Id = DF.df_Id and CDF.col_Id = '14'
    )
    select t.attr_Id,t.attr_Name from t
    inner join dbo.RF_FilterCategory_TFilterAttributes as DF on t.attr_Id = DF.attr_Id
     inner join dbo.T_FilterCategory as FC on DF.fc_Id = FC.fc_Id and FC.fc_Id in 
     (
         select fc.fc_Id from T_Columns as tc
         inner join dbo.RF_Columns_FilterCategory as cdc on tc.col_Id = cdc.col_Id 
        inner join T_FilterCategory as fc on cdc.fc_Id = fc.fc_Id
         where tc.col_Id = '14'
     )
    order by t.sort

  然后就得到如下所有手机类别下的“筛选条件“对应的”筛选条件值“,如下图:







原文地址:https://www.cnblogs.com/zyzlywq/p/2383272.html