[英]Away around Error: There is no unique constraint matching given keys for referenced table
Been at this for some time now.现在已经有一段时间了。 I'm getting this psql error when attepmting to create a joins table (product_type_combo):
尝试创建连接表(product_type_combo)时出现此 psql 错误:
There is no unique constraint matching given keys for referenced table product
引用表产品的给定键没有唯一约束匹配
I'm receiving this because the field (customer) I'm referencing from the table product does not have a UNIQUE constraint.我收到此消息是因为我从表产品中引用的字段(客户)没有 UNIQUE 约束。
CREATE TABLE product
(
id SERIAL PRIMARY KEY,
name VARCHAR(128) NOT NULL,
customer VARCHAR,
CONSTRAINT product_c01 UNIQUE (name)
);
CREATE TABLE product_type_combo
(
customer VARCHAR REFERENCES product(customer),
type_id INT REFERENCES type(id),
PRIMARY KEY (customer, type_id),
CONSTRAINT product_type_combo_c01 UNIQUE (customer, type_id)
);
I don't want to have a UNIQUE constraint on the customer field on the product table since I want duplicates to appear there.我不想对 product 表的 customer 字段设置 UNIQUE 约束,因为我希望重复项出现在那里。 I only want the customer & type combo in the joins table to have a constraint.
我只希望连接表中的客户和类型组合具有约束。
Is there a way around this?有没有解决的办法?
This is silly:这很愚蠢:
customer VARCHAR REFERENCES product(customer),
You have a primary key on the table, an id
column.您在表上有一个主键,一个
id
列。 You should be using that.你应该使用那个。
You could define customer
to be unique
-- the lack of a unique constraint on a column used for a foreign key reference is the cause of the error.您可以将
customer
定义为unique
——用于外键引用的列缺少唯一约束是错误的原因。 However, I strongly, strongly recommend that you use the primary key.但是,我强烈建议您使用主键。
The error is coming from the Foreign Key ( REFERENCES
) constraint, for reasons listed in the PostgreSQL manual :由于PostgreSQL 手册中列出的原因,错误来自外键 (
REFERENCES
) 约束:
A foreign key must reference columns that either are a primary key or form a unique constraint.
外键必须引用作为主键或形成唯一约束的列。
Since your "customer" column is not unique, it cannot be the target of a foreign key reference.由于您的“客户”列不是唯一的,因此它不能成为外键引用的目标。 It also suggests a problem in your data model:
它还表明您的数据 model 存在问题:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.