MariaDB - Create many to many relationship table between two entities [duplicate] - mysql

This question already has answers here:
MySQL Creating tables with Foreign Keys giving errno: 150
(20 answers)
Closed 3 years ago.
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.

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.

Related

Remove primary key(s) - Foreign key constraint is incorrectly formed

I cannot seem to be able to delete primary keys in a table.
All references (FKs) have been removed but it still doesn't let me delete it.
What I'm trying to do is: delete old primary keys to add a new one - but keep the old columns and data (just remove the PK attribute).
What is wrong ?
Table:
CREATE TABLE `employee` (
`User` int(10) unsigned NOT NULL,
`Company` int(10) unsigned NOT NULL,
--unrelated boolean fields
PRIMARY KEY (`User`,`Company`),
KEY `FK_Employee_Company_idx` (`Company`),
CONSTRAINT `FK_Employee_Company` FOREIGN KEY (`Company`) REFERENCES `company` (`ID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `FK_Employee_User` FOREIGN KEY (`User`) REFERENCES `user` (`ID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Trying to delete:
alter table Employee
drop primary key;
Issue:
Error 1025: Error on rename of '.\DB_NAME#sql-3640_4' to '.\DB_NAME\employee' (errno: 150 "Foreign key constraint is incorrectly formed") SQL Statement: ALTER TABLE DB_NAME.employee DROP PRIMARY KEY
Nothing references this table anymore. I also checked via statements which select from information_schema.key_column_usage but yields no results.
Wasted the last hours on Google but can't seem to figure it out.
And if that would work, adding a new column:
alter table Employee
add column ID int unsigned not null auto_increment primary key;
The index is still needed for the existing FK constraints.
Adding the following index (first) should satisfy that requirement:
CREATE INDEX xxx ON employee (User, Company);
Test case

Foreign key constraint does not get executed MySQL. Edit: replaced 'schema' with 'other' [duplicate]

This question already has answers here:
MySQL Error 1215: Cannot add foreign key constraint
(29 answers)
MySQL Creating tables with Foreign Keys giving errno: 150
(20 answers)
Closed 2 years ago.
I am creating 2 tables, customers and orders. The goal is to create a constraint in the orders customers column to only allow insert if customer exists.
Here is the code I am trying
CREATE TABLE other.customers (
customers_id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(45) NULL,
PRIMARY KEY (customers_id)
);
Next I am creating the orders table
CREATE TABLE other.orders (
orders_id INT NOT NULL,
customer INT NOT NULL,
PRIMARY KEY (orders_id),
INDEX customers_idx (customer ASC),
CONSTRAINT customers FOREIGN KEY (customer)
REFERENCES other.customers (customers_id)
ON DELETE CASCADE ON UPDATE CASCADE
);
Both times I get no errors.But his apparently doesn't work and I cannot see the constraint.
So I tried to alter the orders table
ALTER TABLE other.orders ENGINE = InnoDB ;
ALTER TABLE other.orders ADD CONSTRAINT customer
FOREIGN KEY (customer) REFERENCES other.customers (customers_id)
ON DELETE CASCADE ON UPDATE CASCADE;
But this time I get an SQL error:
Operation failed: There was an error while applying the SQL script to the database.
ERROR 1215: Cannot add foreign key constraint
I am probably missing something trivial, but just can't put my finger on it.

MySQL Incorrect Foreign Key with same data type [duplicate]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
MySQL (mariadb Ver 15.1 Distrib 10.1.44-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2) gave me this error:
ERROR 1005 (HY000) at line 129: Can't create table `Houdini`.`stamp` (errno: 150 "Foreign key constraint is incorrectly formed")
when trying to create this table:
DROP TABLE IF EXISTS stamp;
CREATE TABLE stamp (
id INT NOT NULL,
name VARCHAR(50) NOT NULL,
group_id SMALLINT NOT NULL,
member BOOLEAN NOT NULL DEFAULT FALSE,
rank SMALLINT NOT NULL DEFAULT 1,
description VARCHAR(255) NOT NULL DEFAULT '',
PRIMARY KEY(id),
CONSTRAINT stamp_ibfk_1 FOREIGN KEY (group_id) REFERENCES stamp_group (id) ON DELETE CASCADE ON UPDATE CASCADE
);
What is the correct foreign key constraint for this? I presume group_id can't be used for some reason
The foreign keys are members of the primary key of the quest_award_item table, so they must be the same data type as themselves, but that's not the problem.
You seem to think that they must have the same data type as the primary key of their own table, but this is in fact not required.
The requirement is that foreign key column(s) must have the same data type as the column(s) they reference.
In this case, quest_award_item.quest_id must be the same data type as quest.id.
Likewise, quest_award_item.item_id must be the same data type as item.id.
You haven't shown the table definitions of the quest or item tables, so we can only guess at their data types. But one or other other may have an incompatible data type.
Re your comment:
So how do I fix this?
You posted in a comment below that the quest.id column is defined as SERIAL, which MySQL translates into BIGINT UNSIGNED AUTO_INCREMENT.
The foreign key column that references quest.id must be the same data type as the column it references (the AUTO_INCREMENT part is not necessary to match the data type).
So change your CREATE TABLE:
CREATE TABLE quest_award_item (
quest_id BIGINT UNSIGNED NOT NULL,
item_id INT NOT NULL,
PRIMARY KEY (quest_id, item_id),
CONSTRAINT quest_award_item_ibfk_1 FOREIGN KEY (quest_id) REFERENCES quest (id) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT quest_award_item_ibfk_2 FOREIGN KEY (item_id) REFERENCES item (id) ON DELETE CASCADE ON UPDATE CASCADE
);
An alternative solution is to modify the quest.id to be an INT, and then your original CREATE TABLE quest_award_item will work.
ALTER TABLE quest MODIFY COLUMN id INT AUTO_INCREMENT;
But if you already have rows in that table with id values great enough that they need to be BIGINT UNSIGNED (i.e. greater than 231-1), then you can't do that.
could be the data type between the two key are not the same
DROP TABLE IF EXISTS stamp;
CREATE TABLE stamp (
id INT NOT NULL,
name VARCHAR(50) NOT NULL,
group_id INT NOT NULL,
member BOOLEAN NOT NULL DEFAULT FALSE,
rank SMALLINT NOT NULL DEFAULT 1,
description VARCHAR(255) NOT NULL DEFAULT '',
PRIMARY KEY(id),
CONSTRAINT stamp_ibfk_1 FOREIGN KEY (group_id) REFERENCES stamp_group (id) ON DELETE CASCADE ON UPDATE CASCADE
);
if you use int for id you should use int for group_id

Error in foreign key constraint on a dropped table

When I execute the following SQL commands:
CREATE TABLE `TableA` (
`tableAId` INT(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`tableAId`)
);
CREATE TABLE `TableB` (
`tableBId` INT(11) NOT NULL AUTO_INCREMENT,
`tableAId` INT(11) DEFAULT NULL,
PRIMARY KEY (`tableBId`),
CONSTRAINT `FK_TABLE_A_ID` FOREIGN KEY (`tableAId`) REFERENCES `TableA` (`tableAId`)
);
ALTER TABLE `TableB`
RENAME TO `NewTableB`;
ALTER TABLE `TableA`
RENAME TO `NewTableA`,
CHANGE COLUMN `tableAId` `newTableAId` INT(11) NOT NULL AUTO_INCREMENT FIRST;
DROP TABLE IF EXISTS NewTableA;
DROP TABLE IF EXISTS NewTableB;
CREATE TABLE `TableA` (
`tableAId` INT(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`tableAId`)
);
I have the following error on the last command (ie CREATE TABLE TableA (...)) :
Erreur SQL (1005): Can't create table 'TableA' (errno: 150) Foreign
key constraint is incorrectly formed
And when I execute show engine innodb status I have :
------------------------
LATEST FOREIGN KEY ERROR
------------------------
130531 12:06:05 Error in foreign key constraint of table TableB:
there is no index in referenced table which would contain
the columns as the first columns, or the data types in the
referenced table do not match the ones in table. Constraint:
,
CONSTRAINT `FK_TABLE_A_ID` FOREIGN KEY (`tableAId`) REFERENCES `NewTableA` (`tableAId`)
Old question but for others in a similar situation the answer I made at:
https://dba.stackexchange.com/a/87587/56052
may help.
Recreate the table with the same foreign key specification as previous but a
different name.
Drop the resulting table (will also drop original orphan foreign key)
Recreate table with original or no foreign key

Foreign Keys and MySQL Errors

I have the following script to create a table in MySQL version 5.1 which is to refer to 3 other tables. All 3 tables have been created using InnoDB, and all 3 tables have the ID column defined as INT.
I have created other tables successfully which reference ACCOUNT and PERSON, however, this is the first table which references ADDRESS, so I've included the definition for that table, as run, below as well.
The error which I'm getting is ERROR 1005 (HY000) with errno 150, which I understand to be relating to foreign key creation.
The script which fails is (extra columns removed for simplicity):
CREATE TABLE WORK_ORDER (
ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
ACCOUNT_ID INT NOT NULL,
CUSTOMER_ID INT NOT NULL,
SALES_ID INT,
TRADES_ID INT,
LOCATION_ID INT NOT NULL,
INDEX CUST_INDEX(CUSTOMER_ID),
INDEX SALES_INDEX(SALES_ID),
INDEX TRADES_INDEX(TRADES_ID),
INDEX ACCOUNT_INDEX(ACCOUNT_ID),
INDEX LOCATION_INDEX(LOCATION_ID),
FOREIGN KEY (CUSTOMER_ID) REFERENCES PERSON(ID) ON DELETE CASCADE,
FOREIGN KEY (SALES_ID) REFERENCES PERSON(ID) ON DELETE SET NULL,
FOREIGN KEY (TRADES_ID) REFERENCES PERSON(ID) ON DELETE SET NULL,
FOREIGN KEY (ACCOUNT_ID) REFERENCES ACCOUNT(ID) ON DELETE CASCADE,
FOREIGN KEY (LOCATION_ID) REFERENCES ADDRESS(ID) ON DELETE SET NULL
) ENGINE=InnoDB;
The SQL statement used to create the ADDRESS table is below (extra columns removed for simplicity).
CREATE TABLE ADDRESS (
ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
PERSON_ID INT NOT NULL,
ACCOUNT_ID INT NOT NULL,
ADDRESS_L1 VARCHAR(50),
ADDRESS_L2 VARCHAR(50),
CITY VARCHAR(25),
PROVINCE VARCHAR(20),
POSTAL_CODE VARCHAR(6),
COUNTRY VARCHAR(25),
INDEX CUST_INDEX(PERSON_ID),
INDEX ACCOUNT_INDEX(ACCOUNT_ID),
FOREIGN KEY (ACCOUNT_ID) REFERENCES ACCOUNT(ID) ON DELETE CASCADE,
FOREIGN KEY (PERSON_ID) REFERENCES PERSON(ID) ON DELETE CASCADE
) ENGINE=InnoDB;
I've browsed through several questions here dealing with similar issues, but most seem to be duplicate definitions and non-matching field types, as well as some not using InnoDB for one or the other of the tables. However, none of these seem to be the problem. Any ideas?
You can always issue a 'SHOW ENGINE INNODB STATUS' command. Buried in the output will be a "LATEST FOREIGN KEY ERROR" section, which will have more details on exactly what caused the '150' error:
mysql> create table a (x int not null) type=innodb;
Query OK, 0 rows affected, 1 warning (0.02 sec)
mysql> create table b (y int not null, foreign key (y) references a (x) on delete set null) type=innodb;
ERROR 1005 (HY000): Can't create table './test/b.frm' (errno: 150)
mysql> show engine innodb status;
[..... snip snip snip ...]
------------------------
LATEST FOREIGN KEY ERROR
------------------------
091129 16:32:41 Error in foreign key constraint of table test/b:
foreign key (y) references a (x) on delete set null) type=innodb:
You have defined a SET NULL condition though some of the
columns are defined as NOT NULL.
[.... snip snip snip ...]