gpt4 book ai didi

mysql - 如何使用 MySQL 引用带有外键的复合主键

转载 作者:行者123 更新时间:2023-11-29 23:26:50 25 4
gpt4 key购买 nike

我正在尝试在表 cell_lines 中设置一个外键,该外键将引用表 topographic_regions 中复合主键的 topographic_region 列.

每次运行最后三行代码尝试添加外键时,我都会收到错误代码 1215:无法添加外键约束。

现在,cell_lines 中的外键列名称 (topographic_region) 仅与 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);

最佳答案

这是复合 PK 的问题。事实上,您的自动编号 tographic_region_id 将是唯一的,您应该将其用于 PK 和 FK。 topographic_region 听起来它也是唯一的,因此您应该为其添加唯一索引。

关于mysql - 如何使用 MySQL 引用带有外键的复合主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26891456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com