我怎么能构建这个数据库?

时间:2014-02-24 22:34:17

标签: sql database-design

我们有一个数据库,每个数据库都有一堆类别。层次结构如下:

Department
-- Necklaces
   -- N_Diamond
      -- N_D_Silver
   -- N_Silver
-- Rings
   -- R_Diamond
   -- R_Gemstone

每个顶级类别(项链,戒指)都有一个父类别(部门),这些顶级类别中的每个类别只有一个父类别(即N_Diamond是N_D_Silver的父级)。

在每个类别中,都会有一个产品列表。每个产品可以属于多个类别(一对多?)。

如何在数据库中组织此操作?产品的表格,每行是产品+它所属的类别?这意味着每个产品可以有多行。不过,这似乎并不是很正常化。

3 个答案:

答案 0 :(得分:0)

好吧,使用树形结构 表格包含rows idparent_categorychild_category。 所以典型的行是

1, Departments, Necklace
2, Departments, Rings
3, Neckless, N_Diamonds
3, Neckless, N_Silver
...
10, R_Gemstone, null

您可以通过编制索引来规范化。

现在为引用上面树的产品创建一个表 Product_Table rows idcategory_idproduct_name

答案 1 :(得分:0)

可以简单地说:

Product (ProductID, Name, details)
Department (DepartmentID, DepartmentName, ParentDepartmentID)
ProductDepartment (DepartmentID, ProductID)

您可以将部门级别的层次结构分成不同的表格,理想情况取决于使用情况。

答案 2 :(得分:0)

我会按照以下方式对其进行建模:

create table dbo.Type
(
  id int not null identity(1,1) primary key ,
)

create table dbo.TypeAttribute
(
  typeId int not null foreign key references dbo.Type(id) ,
  id     int not null identity(1,1) unique ,

  primary key ( typeId , id ) ,

)

create table dbo.Product
(
  id     int not null identity(1,1) unique ,
  typeId int not null foreign key references dbo.Type(id) ,

  primary key ( id , typeId ) ,
)

create table dbo.ProductAttribute
(
  productId   int not null ,
  typeId      int not null ,
  attributeId int not null ,

  primary key ( productId , typeId , attributeId ) ,
  foreign key ( productId , typeId      ) references dbo.Product       ( id     , typeId ) ,
  foreign key ( typeId    , attributeId ) references dbo.TypeAttribute ( typeId , id    ) ,

)
  • 我们有一组独特的Types,即产品的父类别。
  • 每个此类Type都有一些TypeAttributes个特定类型项目的描述性属性。
  • 我们有多个Products,每个Type被分配给一个且只有一个ProductAttribute
  • 我们有一个关联实体Type,枚举每个唯一产品所拥有的属性,这些属性来自该产品{{1}}的可用属性。
相关问题