【问题标题】:Unable to create foreign key mysql无法创建外键mysql
【发布时间】:2018-01-09 21:55:07
【问题描述】:

错误码:1215:无法添加外键约束

我已经尝试了所有选项,例如使用更改默认存储引擎

SET default_storage_engine=ENGINE

但我无法创建这个外键约束。我正在使用 Mysql 5.5。 任何人都可以帮助我。

create table if not exists pallets(
    palletId serial,
    goodsType varchar(25),
    desitination varchar(25),
    primary key (palletId)
);
create table if not exists storage(
    id serial,
    palletId integer,
    primary key (id),
    constraint FK _Pallet foreign key (palletId) REFERENCES pallets(palletId)
);

【问题讨论】:

  • 两列必须具有相同的数据类型。 Integerserial 不同。所以尝试bigint unsigned 而不是integer(或在pallets 中使用integer)。

标签: mysql sql foreign-keys unique-constraint


【解决方案1】:

外键列的数据类型必须匹配被引用表中被引用(通常是主键)列的数据类型。

错误 1215 是我们尝试创建违反此限制的外键约束时的预期行为。

根据 MySQL 参考手册https://dev.mysql.com/doc/refman/5.6/en/numeric-type-overview.html

SERIALBIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE 的别名。


所以pallets的表定义等价于:

create table pallets
( palletId   BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE
  --         ^^^^^^^^^^^^^^^  
, ...
, primary key (palletId)
);

外键引用必须是相同的数据类型BIGINT UNSIGNED

例如

create table storage
( id ...
, palletId   BIGINT UNSIGNED 
  --         ^^^^^^^^^^^^^^^
, primary key (id)
, constraint FK_storage_pallets foreign key (palletId) REFERENCES pallets(palletId)
);

【讨论】:

    【解决方案2】:

    这个问题之前在堆栈溢出中被问过,你可能想检查一下:Error Code: 1215. Cannot add foreign key constraint (foreign keys)

    【讨论】:

      【解决方案3】:

      如果您使用 SERIAL 数据类型作为主键,则外键应为 BIGINT UNSIGNED

      create table if not exists pallets(
          palletId serial,
          goodsType varchar(25),
          desitination varchar(25),
          primary key (palletId)
      );
      create table if not exists storage(
          id serial,
          palletId bigint unsigned,
          primary key (id),
          constraint FK _Pallet foreign key (palletId) REFERENCES pallets(palletId)
      );
      

      【讨论】:

        猜你喜欢
        • 2013-10-05
        • 1970-01-01
        • 2012-04-23
        • 2014-02-26
        • 2020-08-14
        • 2015-06-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多