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

nca*_*sch 4 mysql foreign-keys primary-key

我在 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)
 );
Run Code Online (Sandbox Code Playgroud)

处理的时候出现这个错误:

错误代码:3780。引用列“location_id”和外键约束“departments_ibfk_1”中引用的列“location_id”不兼容。

两个表中 location_id 的数据类型相同。我找不到错误。

小智 11

我自己最近也遇到了类似的问题。我所做的是

  1. 使用 MySQL 命令检查我的两个表的描述

    SHOW FULL COLUMNS FROM first_table;

    SHOW FULL COLUMNS FROM second_table;

然后(至少就我而言):

  1. 我立即发现我的参考列的排序规则不同( first_table 中的utf8mb4_unicode_ci和secondary_table 中的utf8mb4_0900_ai_ci)。

最后:

  1. 解决方案是更改两个表中的排序规则。
    ALTER TABLE first_table
    MODIFY COLUMN column_name varchar(60)
    COLLATE utf8mb4_0900_ai_ci;
    
    Run Code Online (Sandbox Code Playgroud)

或者

    ALTER TABLE second_table
    MODIFY COLUMN column_name varchar(60)
    COLLATE utf8mb4_unicode_ci;
Run Code Online (Sandbox Code Playgroud)