【问题标题】:ERROR 3780: Referencing column and referenced column in foreign key constraint are incompatibleERROR 3780:外键约束中的引用列和被引用列不兼容
【发布时间】:2021-11-14 06:50:22
【问题描述】:

我在 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。引用列“location_id”并引用 外键约束“departments_ibfk_1”中的“location_id”列 不兼容。

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

【问题讨论】:

  • 我可以完美地执行查询吗?两个表都被创建并且外键存在?我能想到的唯一另一件事是确保两个表具有相同的排序规则。
  • 为什么departments.location_id 声明为UNIQUE?一个地点不能有多个部门吗?

标签: mysql foreign-keys primary-key


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    如果数据类型为“string/char”类型,请检查两个相关字段的“charter set”和“collat​​ion”。

    整数数据类型上不存在这样的问题(“外键约束'xxx'不兼容”)(或者至少我没有遇到这样的不兼容问题)。

    有时创建的表与外部表(由其他人创建的外部表,从旧转储恢复等)具有不同的“章程集/排序规则”。

    如果创建新表(charter/collat​​ion 与外表相同):

    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 ;
    

    【讨论】:

      猜你喜欢
      • 2020-08-01
      • 2021-08-31
      • 1970-01-01
      • 2020-05-22
      • 1970-01-01
      • 2020-12-14
      • 2019-06-23
      • 2021-06-01
      • 2016-06-11
      相关资源
      最近更新 更多