1

我的PostgreSQL 9.2.3数据库中有大约 50 种产品类型。

其中有些是可分的,有些则不是。

更复杂的是,"volume"不同的产品应该有不同的精度。

Product type 1: allowed 8 decimal places.
Product type 2: only integer values.
Product type 3: 2 decimal places
Product type 4: 2 decimal places
Product type 5: 3 ---- || ------
Product type 6: 4 ---- || ------
Product type 7: 16 ---- || -----
Product type 8: integer values
Product type 9: 4 decimal places
Product type 10: 5 decimal places
Product type 11: 12 decimal places

还有"orders"一个表,一个用于所有产品的表,其中几乎所有列都是相同的(用户、承包商、订单日期、运费等)。唯一的例外是"volume"列。

我应该使用什么数据类型?

我考虑过"numeric"为所有产品类型使用字段 + 存储每种产品类型的精度信息,并将“订单寄存器”视图中的值转换为所需的精度,但这不会导致数据一致性失败吗?

在此解决方案中,无法检查例如“产品类型 8”的整数值是否为整数,我仅将其显示为整数。:(

另一种方法是为每种数据类型创建一个列,例如volume_int、volume_num_2、volume_num_5 等,这真的很糟糕。:(

...另一种解决方案是使用表继承,如下所示:

orders <- volume is integer
orders_product_1 (inherits orders) <- volume is numeric(24,8)
orders_product_2 (inherits orders) <- volume is integer
orders_product_3 (inherits orders) <- volume is numeric(20,2)

...但是创建大约 20 个继承的表似乎是形式对内容的胜利...

最好的解决方案是什么?也许还有另一种解决问题的方法?

4

2 回答 2

2

使用NUMERIC任何值所需的最大比例和精度。

如果精度是完全静态的并且由同一个表中的另一个字段定义,则可以使用一个CHECK约束或一系列约束来强制执行有关值的规则。

如果不查找另一个表就无法找到 precsions,您将需要使用触发器来强制执行规则。

我看到的唯一替代方案是CREATE TYPE复合类型,它具有一个值和一个存储在它旁边的单位/精度。这似乎是沉重的,并且会很痛苦。

于 2013-09-04T09:24:52.187 回答
1

我会说使用带有精度信息的数字字段和表格的第一个解决方案。在这种情况下,您也可以稍后根据需要更改精度。
或者您可以将所有数据存储为整数并将系数存储在某个表中并计算您的字段value * coefficient(可能是 1、0.01 等)

于 2013-09-04T08:59:07.450 回答