[英]MySQL One-To-Many Foreign Key strategy
I have a table: 我有一张桌子:
instances 实例
with the PK called 'id' (int autoincrement) PK称为“ id”(int自动增量)
and two other tables: 和另外两个表:
values_text values_text
values_int values_int
these 2 tables have these fields: 这两个表具有以下字段:
instance_id / code / value instance_id /代码/值
with a PK made by instance_id and code . 由instance_id和code制作的PK。
A record of instance can have 0, 1 or many related records in values_text and values_int . 实例的记录可以在values_text和values_int中具有0、1或许多相关记录。
I want to add foreign keys from instances to values_int and values_text so that when I delete a record from instances the related records are deleted too from values_text and values_int . 我想将实例的外键添加到values_int和values_text中,以便当我从实例中删除记录时,相关记录也将从values_text和values_int中删除。
I was able to create the foreign keys, the problem is that I can't create a record in instance table because I get the error: 我能够创建外键,问题是由于出现错误,我无法在实例表中创建记录:
Cannot add or update a child row: a foreign key constraint fails ( instances
, CONSTRAINT instances_fk_ab43df
FOREIGN KEY ( id
) REFERENCES values_text
( instance_id
)) 无法添加或更新子行:外键约束失败(
instances
,CONSTRAINT instances_fk_ab43df
FOREIGN KEY( id
)参考values_text
( instance_id
))
How can I set correctly the foreign keys? 如何正确设置外键?
you have created the PK/FK
vice versa, in fact your foreign key is instance_id
(in both values_text
and values_text
tables) not id
in instances
. 您所创建的
PK/FK
反之亦然,其实你的外键是instance_id
(无论是在values_text
和values_text
表)没有id
的instances
。
remove the foreign key constraint on id
in instances
instead of it make the foreign key constraint on instance_id
(in both values_text
and values_text
tables) and also leave id
in instances
as primary key. 删除
instances
对id
的外键约束,而不是对instance_id
(在values_text
和values_text
表中)都进行外键约束,并将instances
id
保留为主键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.