0

我有一张桌子tablet,有一列period_id。表和tablet表是多对一的关系,period表和period表是一对多的关系sub_period。我需要能够sub_period在 或 from 中指定单个条目tablet,其选择受period条目限制,但由于sub_period仅取决于period,因此我不能。我应该如何建模?

在我的模型中,每一tablet行都应该有一个period条目和一个sub_period条目。periodsub_period应该的关系1:n(一个时期可能有很多子时期,但每个子时期只能属于一个时期)。sub-period我希望能够从中选择的stablet应该受到我选择的限制period

编辑:已经意识到我需要tablet和之间的 N:1 关系period:许多平板电脑可以与同一时期相关。

4

3 回答 3

2

has_tablet ENUM('1')在 中创建一个可为空的列sub_periodUNIQUEsub_period (period, has_tablet).

has_tablet只能接受值1,或者NULL这意味着您可以将每个时期的一个季节设置为“拥有平板电脑”。由于periodtotablet是一对一的,因此这也唯一标识了 the tablettoo。

使用此解决方案,可以在一段时间内完全不设置任何平板电脑。如果有问题,请添加periodtablet参考。tablet (period, sub_period)sub_period (period, sub_period)

这是一种非规范化,但它永远不会导致不一致(因为在两个表中都period定义了)。sub_period

更新:

似乎那个时期对平板电脑是一对多的。在这种情况下,只需添加 make tabletreferencesub_period而不是period. period关系可以通过简单的连接来传递推断。

于 2012-05-31T14:58:17.867 回答
0

Then you have 2 options:

  • database layer: implement consistency contraints through triggers. after insert or update, if sub_pediod is not a sub_period of the tablet's period, raise the appropriate error.
  • applicative layer: implement the proper GUI to provide the right choices only, whenever it is necessary.

The second option is my favorite whenever it is about non sensitive data (keep in mind somebody could always skip the client interface), because it usually gives me more "range of motion" with how I want to deal with the problem. Of course there are always exceptions...

于 2012-05-31T14:48:55.510 回答
0

当你为你建模时,通常你不会创建 1:1 关系,当你规范化时你会注意到关系为 1:1 的表你可以将它们匹配到一个表中,这就是我的看法:如果你有 3 个有关系的表

  • 平板电脑1:n sub_period
  • 平板电脑1:1时期

(图中的键是主键,红色符号是外键)

在此处输入图像描述

或者您可以在TabletPeriod表之间进行匹配,模型将如下所示

在此处输入图像描述

平板电脑吸收了Period的所有属性,但这取决于您,您必须根据自己的需要调整模型。

于 2012-05-31T14:52:23.047 回答