2012-07-15 50 views
1

我目前有一个表占多数(如99%)的一个字段的数据依赖于一个字段,但其他1%依赖于其他字段。如何设计一个具有类似条目的数据库表

例如,我有以下的价格表

product PK 
color PK 
cost 

以下是该表中某些条目

product|color|cost 
pen|red|$1.00 
pen|blue|$1.00 
pen|green|$1.00 
etc.... 
pen|black|$0.90 
pen|white|$0.85 
pencil|red|$0.50 
pencil|blue|$0.50 
pencil|green|$0.50 
etc... 
pencil|black|$0.35 
pencil|gray|$0.40 

我与此表时遇到的问题是,每当我有添加一个产品或颜色我必须添加数百个类似的条目到这个表。

我目前想存储通过以下方式

pen|all_other_colors|$1.00 
pen|black|$0.90 
pen|white|$0.85 
pencil|all_other_colors|$0.50 
pencil|black|$0.35 
pencil|gray|$0.40 

我在正确的轨道上或有更好的数据库设计,处理这个问题的数据?任何帮助或链接将不胜感激。我无法为这个问题找到正确的措辞。

+0

获取信息可能你总结你的问题?是不是要单独管理每个价格?或者?即使没有价格,您也需要管理哪些产品组合可用 – 2012-07-15 16:30:59

+0

在我的设计中,我假定产品在颜色表中可以有任何颜色。我希望减少插入数百种产品颜色组合条目的需求(每次我添加一个新产品(经常发生),并且只处理产品颜色组合的定价例外情况(这很少见)。您的答案是那种我正在寻找的东西。我可能会用一个“异常”表,但我不确定是否违反了任何数据库设计理论。谢谢您的帮助! – 2012-07-15 20:20:31

回答

0
  • BaseProduct拥有的所有产品名称及其价格
  • Product拥有所有可用的有效产品的色彩组合
  • ColorPrice是从基础价格上的差异(偏移)。
  • ColorCharge具有有例外定价仅行(没有行的ColorPrice = 0)

enter image description here

要为特定基础产品(specific_prodict_id

select 
     b.ProductName 
    , c.ColorName 
    , b.ProductPrice + coalesce(x.ColorPrice, 0.0) as ProductPrice 
from  Product  as p 
join  BaseProduct as b on b.BaseProductID = p.BaseProductID 
join  Color  as c on c.ColorId  = p.ColorId 
left join ColorCharge as x on x.BaseProductID = p.BaseProductID and x.ColorID = p.ColorID 
where p.BaseProductID = specific_prodict_id; 
1

您需要规范化的数据库表

突破它在如下三个表:

产品

id | product 

颜色

id | color 

product_cost

id | Product_id | color_id | Cost 
+0

我确实有产品表和颜色表,但我仍然有同样的问题。向产品表中添加一个条目迫使我为product_cost表创建数百个类似的条目。 – 2012-07-15 13:43:00

+0

他们将不会类似使用每个产品的唯一主键 - 颜色 - 成本组合 – Lucifer 2012-07-15 13:47:05

+0

如果我向产品表中添加标记等产品,并且颜色表中的数百种颜色的标记价格相同除了颜色为黑色和红色的标记外,正确的方法是将数百个条目添加到product_cost表中? – 2012-07-15 13:59:41

0

你可以组的颜色放在一起,然后将价格为整个集团:

enter image description here

而且你的例子可以类似地表示这个...

PRICE: 

    PRODUCT_ID GROUP_ID PRICE 
    pen   1   $1.00 
    pen   2   $0.90 
    pen   3   $0.85  
    pencil  1   $0.50 
    pencil  2   $0.35 
    pencil  4   $0.40 

GROUP: 

    GROUP_ID 
    1 
    2 
    3 
    4 

COLOR_GROUP: 

    GROUP_ID COLOR_ID 
    1   red 
    1   blue 
    1   green 
    2   black 
    3   white 
    4   gray 

COLOR: 

    COLOR_ID 
    red 
    blue 
    green 
    black 
    white 
    gray 

增加的复杂性是否值得它取决于你...

相关问题