2

I am having a problem creating a many to many relationship table in MariaDB. I have tried using the workbench, manual creation scripts and the "Show Create Table xxxxxxx;" from another already created n to n tables but the result is always the same, the following error:

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

The code I am using to create the table:

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

I have tried running this in two different versions of MariaDB, 10.0.38 and 5.5.60 but I keep getting the same error.

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
Guido
  • 81
  • 2
  • 9

1 Answers1

4

This is a very short example:

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)
);

And remember, Table1 and Table2 primary key have to be same type of Table3 foreign key.

Graiton
  • 78
  • 7