我正在马里兰州的约翰斯霍普金斯大学学习数据库课程并且有一个问题。我已经发邮件给我的教授,他知道我在这里问这个问题,他很酷。所以我在Postgres开发了一个COOKBOOK数据库,并且我在Postgres中遇到了一个有趣的问题,我似乎无法构建PRICE表。我有一个不错的食谱ERD,但显然不能发布,直到我的声誉至少10。我会尽我所能来形容ERD。有三个与价格相关的保理表格。这些是成分,替代品和价格。Postgres综合主键依赖问题
下面是对ERD的链接(注意1:M为配料替代): [ERD]
我可以有一个成分与潜在的许多替换和可能的一个到一个取代之间和价格(如果知道价格,每个替代品一个价格)。如果PRICE已知,则PRICE能够定义具有复合主键的元组:(price_id,ingredient_id(fk),substitution_id(fk))
我面临的挑战是Postgres SQL不允许我建立这种关系,我不确定为什么。我已经将SUBSTITUTION中的键设置为具有UNIQUE约束,所以不应该成为问题。我唯一能想到的是,SUBSTITUTION中的ingredient_id是INGREDIENT的外键,因此可能不会在SUBSTITUTION中物理建立,但我得到的错误并不表明这一点。这是我在终端我得到(第一描述代换):
cookbook=# \d+ SUBSTITUTION
Table "public.substitution"
Column | Type | Modifiers | Storage | Description
--------------------+-----------------------+--------------------------------------------------------------------------+----------+-------------
substitution_id | integer | not null default nextval('subsitution_substitution_id_seq'::regclass) | plain |
ingredient_id | integer | not null default nextval('subsitution_ingredient_id_seq'::regclass) | plain |
name | character varying(50) | not null | extended |
measurement_ref_id | integer | not null default nextval('subsitution_measurement_ref_id_seq'::regclass) | plain |
metric_unit | character varying(25) | not null | extended |
Indexes:
"subsitution_pkey" PRIMARY KEY, btree (substitution_id, ingredient_id)
"uniqueattributes" UNIQUE, btree (substitution_id, ingredient_id)
Foreign-key constraints:
"subsitution_ingredient_id_fkey" FOREIGN KEY (ingredient_id) REFERENCES ingredient(ingredient_id)
"subsitution_measurement_ref_id_fkey" FOREIGN KEY (measurement_ref_id) REFERENCES measurement_ref(measurement_ref_id)
Has OIDs: no
cookbook=# create table price(
price_id serial not null,
ingredient_id serial references substitution(ingredient_id),
cookbook(# substitution_id serial references substitution(substitution_id),
cookbook(# usdollars smallint not null,
cookbook(# availability season,
cookbook(# seasonal boolean,
cookbook(# primary key (price_id, ingredient_id, substitution_id)
cookbook(#);
NOTICE: CREATE TABLE will create implicit sequence "price_price_id_seq" for serial column "price.price_id"
NOTICE: CREATE TABLE will create implicit sequence "price_ingredient_id_seq" for serial column "price.ingredient_id"
NOTICE: CREATE TABLE will create implicit sequence "price_substitution_id_seq" for serial column "price.substitution_id"
NOTICE: CREATE TABLE/PRIMARY KEY will create implicit index "price_pkey" for table "price"
ERROR: there is no unique constraint matching given keys for referenced table "substitution"
我不知道我是否真的理解,外键在它自己的表中必须是唯一的,如果你想引用元组:substitition_id和ingredient_id,你可以添加一个像'ingredient_subtition_id'这样的列作为连续序列到你的'替代'表,并将其作为主键,则可以将此键作为“价格”表中的外键引用。 – Houari 2014-10-28 20:50:41
@Houari添加一个键&FK并不能阻止PRICE(substitution_id,ingredient_id)对SUBSTITUTION的限制。你的建议所做的是有一个FK存在,但没有影响是原始预期约束点。 – philipxy 2014-11-08 09:41:29