简体   繁体   中英

Unique constraint on single field of a custom type in postgres

I have an entity price in my schema it has an attribute amount which is of a custom type money_with_currency .

The money_with_currency is basically type (amount Big Int, currency char(3)).

The price entity belongs to a product. What I want to do is, create a unique constraint on the combination of product_id(foreign key) + currency . How can I do this?

Referencing a single field of a record type is a bit tricky:

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM