我试图在表topographic_region cell_lines中设置一个外键,它将引用表topographic_regions.中复合主键的列
每次我运行最后三行试图添加外键的代码时,我都会收到错误代码1215:无法添加外键约束。
现在,(topographic_region) cell_lines中的外键列名仅与topographic_regions,中的一个复合主键列名相匹配,而另一个复合主键列名为topographic_region_id.。在创建外键时,我通常需要处理复合主键的两个组件吗?
后续问题是,我实际上已经尝试使用复合外键约束来处理复合主键的两个组件,并且仍然收到了一个错误代码1215:无法添加外键约束。
我能做些什么来解决这个问题,你是否希望我提供更多的信息来解决这个问题?我很乐意回应。
感谢您的阅读。我对mySQL非常陌生。
create table topographic_regions(
topographic_regions_id int not null auto_increment,
topographic_region int(10),
karyotypes varchar(255),
constraint pk_topographicID primary key (topographic_regions_id, topographic_region)
);
create table cell_lines(
cell_lines_id int not null auto_increment,
cell_line varchar(50),
topographic_region int(10),
constraint pk_cellID primary key (cell_lines_id, cell_line)
);
alter table cell_lines
add foreign key (topographic_region)
references topographic_regions(topographic_region);发布于 2014-11-12 16:18:29
这就是复合PKs的问题所在。事实上,您的自动编号topographic_region_id将是唯一的,您应该使用它的PK和FK。topographic_region听起来似乎也是唯一的,所以您应该为它添加一个唯一的索引。
发布于 2014-11-21 19:43:35
外键是指某些列,其子行值必须以子行值的形式出现在另一个表中,其中它们是候选键。如果您确实有一个从cell_lines到topographic_regions的外键,那么cell_lines将有一个topographic_region_name列,您需要:
alter table cell_lines
add foreign key (topographic_regions_id, topographic_region)
references topographic_regions(topographic_regions_id, topographic_region);我怀疑( topographic_regions_id,topographic_region)不是topographic_regions的候选键,而且仅仅因为决定cell_lines没有topographic_region列,topographic_regions_id就足以识别一个区域。虽然它可能是一个细胞系不确定一个特定的地形区域。但是topographic_regions_id在cell_lines中不是外键,因为它不是topographic_regions中的密钥。(在SQL中没有一种简单的方法来约束某些列的子行值必须显示为另一个表中的子行值,因为它们不是候选键的超集。)
如果topographic_regions_id在topographic_regions中是唯一的,那么它是一个候选键,应该声明为唯一,而不是NULL。如果topographic_region_name在topographic_regions中是唯一的,那么它是一个候选键,应该声明为唯一,而不是NULL。如果两者都是候选密钥,则(topographic_regions_id,topographic_region)不是候选密钥。您可以选择一个候选键来声明主键,这仅仅意味着唯一,而不是NULL。cell_line也是。因为您的_id列是auto_increment,所以我怀疑它们是唯一的,在这种情况下,两个表都没有复合候选键。
(所有这些假设所有列都不能为空。)
https://stackoverflow.com/questions/26891456
复制相似问题