mysql 错误3780:引用列和外键约束中的被引用列不兼容

kxkpmulp  于 2022-12-17  发布在  Mysql
关注(0)|答案(3)|浏览(930)

我在MySQL 8.0中创建了一个名为hr的模式。一个是locations,另一个是departments,后者有一个外键引用表locations

create table hr.locations(
location_id varchar(4) not null unique,
street_address varchar(25) not null,
country_id char(2) not null unique,
primary key(location_id),
foreign key(country_id) references countries(country_id)
);

create table hr.departments(
department_id varchar(4) not null unique,
department_name varchar(30) not null,
manager_id varchar(9) not null unique,
location_id varchar(4) not null unique,
primary key(department_id),
foreign key(location_id) references locations(location_id)
 );

处理时出现此错误:
错误代码:3780。外键约束'departments_ibfk_1'中的引用列'location_id'和被引用列'location_id'不兼容。
两个表中location_id的数据类型相同,我找不到错误。

3z6pesqy

3z6pesqy1#

您是否尝试过将location_id定义为char(4)?当然,在两个表中都是如此。

20jt8wwn

20jt8wwn2#

如果数据类型为“字符串/字符”类型,请检查两个相关字段的“章程集”和“排序规则”。
在整数数据类型上没有这样的问题(“外键约束'xxx'不兼容”)(或者至少我没有遇到过这样的不兼容)。
有时创建的表具有与外部表不同的“章程集/排序规则”(外部表由其他人创建,从旧转储恢复等)。
如果创建新表(章程/排序与外来表相同):

CREATE TABLE IF NOT EXISTS `hr`.`locations`  (
    ...
)
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_unicode_ci;

如果两个表都已存在,并且要更改一列:

ALTER TABLE `hr`.`locations` 
CHANGE COLUMN `location_id` `location_id` varchar(4) 
CHARACTER SET 'utf8mb4'
COLLATE 'utf8mb4_unicode_ci' NOT NULL ;
lf5gs5x2

lf5gs5x23#

当其中一个属性标记为“未签名”,而另一个标记为“已签名”时,我遇到了这个问题。更改这两个属性以匹配“未签名/已签名”状态修复了该错误。

相关问题