错误代码: 1215:无法添加外键约束
我已经尝试了所有的选项,比如使用
SET default_storage_engine=ENGINE但我无法创建这个外键约束。我正在使用MySQL5.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)
);发布于 2018-01-09 22:14:36
外键列的数据类型必须与引用表中引用的(通常是主键)列的数据类型相匹配。
错误1215是当我们试图创建违反此限制的外键约束时的预期行为。
根据MySQL参考手册https://dev.mysql.com/doc/refman/5.6/en/numeric-type-overview.html
SERIAL 是 BIGINT 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)
);发布于 2020-09-28 04:59:24
如果使用串行数据类型作为主密钥,则外键应为BIGINT无符号。
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)
);https://stackoverflow.com/questions/48177217
复制相似问题