MariaDB-在两个实体之间创建多对多关系表

时间:2019-06-07 15:48:27

标签: mysql sql foreign-keys mariadb

我在MariaDB中创建多对多关系表时遇到问题。 我尝试使用工作台,手动创建脚本和“显示创建表xxxxxxx;”。从另一个已经创建的n到n个表中,但是结果始终相同,出现以下错误:

Error Code: 1005. Can't create table `asi_234_api_establecimientos`.`oe_modalidad` (errno: 150 "Foreign key constraint is incorrectly formed")

我用来创建表格的代码:

CREATE TABLE `oe_modalidad` (
  `oferta_establecimiento_id` bigint(20) NOT NULL,
  `modalidad_id` bigint(20) NOT NULL,
  KEY `fk_oe_modalidades_oferta_establecimiento1_idx` (`oferta_establecimiento_id`),
  KEY `fk_oe_modalidad_modalidad1_idx` (`modalidad_id`),
  CONSTRAINT `fk_oe_modalidad_modalidad1` FOREIGN KEY (`modalidad_id`) REFERENCES `modalidad` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `fk_oe_modalidades_oferta_establecimiento1` FOREIGN KEY (`oferta_establecimiento_id`) REFERENCES `oferta_establecimiento` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB

我尝试在MariaDB的两个不同版本10.0.38和5.5.60中运行此程序,但我一直遇到相同的错误。

1 个答案:

答案 0 :(得分:1)

这是一个非常简短的示例:

create table Table1(
    id int auto_increment key,
    name varchar(50) not null
);

create table Table2(
    id int auto_increment key,
    name varchar(50) not null
);

create table Table3(
    idTable1 int not null,
    idTable2 int not null,
    primary key(idTable1, idTable2),
    CONSTRAINT fk_table3_table1 foreign key (idTable1) references Table1 (id),
    CONSTRAINT fk_table3_table2 foreign key (idTable2) references Table2 (id)
);

请记住,Table1和Table2主键必须与Table3外键类型相同。