【问题标题】:Unique constraint on single field of a custom type in postgrespostgres中自定义类型的单个字段的唯一约束
【发布时间】:2018-03-27 03:11:24
【问题描述】:
我的架构中有一个实体价格,它有一个属性amount,它属于自定义类型money_with_currency。
money_with_currency 基本上是类型(金额 Big Int,货币 char(3))。
价格实体属于产品。我想要做的是,在 product_id(foreign key) + currency 的组合上创建一个 唯一约束。我该怎么做?
【问题讨论】:
标签:
postgresql
unique-constraint
【解决方案1】:
引用记录类型的单个字段有点棘手:
CREATE TYPE money_with_currency AS (amount bigint, currency char(3));
CREATE TABLE product_price
(
product_id integer not null references product,
price money_with_currency not null
);
CREATE UNIQUE INDEX ON product_price(product_id, ((price).currency));