【问题标题】:Can Database Normalization occur from values数据库规范化可以从值发生吗
【发布时间】:2013-04-22 09:36:30
【问题描述】:

假设我想规范化一个表格

itemID | itemDate | itemSource | type | color | size | material
 254    03/08/1988    toyCo      doll   null     16    plastic
 255    03/08/1988    toyCo      car    blue     null  plastic
 256    03/08/1988    toyCo      boat   purple   20    wood

现在类型字段只能有 3 个值中的 1 个。 doll, car, or boatcolor, size, and material 的属性在功能上依赖于 type。正如您所看到的,type|doll 的项目不能确定color。我不知道这是否是一个问题。但继续前进。

type(pk) | color | size | material = 表 A

itemID(pk) | itemDate | itemSource = 表 B

我们现在是 1nf。 我的问题是type 键及其属性是否可以基于类型键的可能值?

typeDoll(pk) | size | material = 表 C

typeCar(pk) | color| material = 表 D

typeBoat(pk) | color | size | material 表 E

【问题讨论】:

  • 但是C、D、E表都变成了一行的表,都具有相同的列结构和相同的列之间的功能依赖。你为什么追这棵树?你想达到什么目的?
  • 他们不会是一排。可以有很多dolls, cars, and boatstable C可以拥有多排不同颜色和材质的娃娃。我追逐这棵树的原因是:我想要纯数据表。如果稍后我将foo, foo2, foo3, foo4 等列引入table A 但这些列仅对具有typedoll 的行有用,那么这意味着我可以创建boatcar 具有空或空的行foo, foo2, foo3, foo4 的值。我认为这是浪费。我说的对吗?
  • 大脑放屁警报!你当然是对的。但是,它们保持相同的列结构,具有相同的功能依赖关系。我相信你过度概括了。由于表 B 是一个查找表,除了它自己的维护之外,如果需要,它可以很容易地在以后被视图替换。从 C、D、E 开始作为基表 B 上的视图,如有必要,可将其反转。
  • 我不认为它过于笼统。我要实现的目标称为多态性。它有很好的OOB用途。我想将一个外键限制为许多可能的表键。
  • 我仍然认为你是想钉钉子。

标签: sql database-design entity-relationship normalization


【解决方案1】:

我不确定我是否完全理解您的要求,但这是在 SQL 中创建独占弧的一种方法。

-- Columns common to all types.
create table items (
  item_id integer primary key,
  item_type varchar(10) not null
    check (item_type in 'doll', 'car', 'boat'),

  -- This constraint lets the pair of columns be the target of a foreign key reference.
  unique (item_id, item_type),

  item_date date not null default current_date,
  item_source varchar(25) not null
);

-- Columns unique to dolls. I'd assume that "size" means one thing when you're
-- talking about dolls, and something slightly different when you're talking
-- about boats.
create table dolls (
  item_id integer primary key,
  item_type varchar(10) not null default 'doll'
    check(item_type = 'doll'),
  foreign key (item_id, item_type) references items (item_id, item_type),
  doll_size integer not null 
    check(doll_size between 1 and 20),
  doll_material varchar(25) not null  -- In production, probably references a table 
                                      -- of valid doll materials.
);

dolls.item_type 列及其 CHECK 约束和外键引用保证了

  • “娃娃”中的每一行在“项目”中都有匹配的行,并且
  • 匹配的行也是关于娃娃的。 (与船或汽车无关。)

船和汽车的桌子是相似的。

如果您必须在 MySQL 中实现这一点,则必须替换 CHECK 约束,因为 MySQL 不强制执行 CHECK 约束。在某些情况下,您可以将它们替换为对小表的外键引用。在其他情况下,您可能需要编写触发器。

【讨论】:

    【解决方案2】:

    我想要达到的目标叫做多态关联。这可以通过创建一个超级表来存储所有可能的列并使用第二个和第三个表将外键限制为主键来实现。

    详细解释here

    【讨论】:

      猜你喜欢
      • 2018-01-27
      • 2014-04-01
      • 1970-01-01
      • 2011-01-11
      • 2012-10-08
      • 2012-06-21
      相关资源
      最近更新 更多