MySQL can't create table with foreign key - mysql

CREATE TABLE `assessmentbookdb`.`MCQs` (
`id` INT NOT NULL AUTO_INCREMENT ,
`MCQAnswer` VARCHAR(200) NOT NULL ,
`QuestionID` INT NOT NULL ,
PRIMARY KEY (`id`) ,
INDEX `QuestionID` (`QuestionID` ASC) ,
CONSTRAINT `QuestionID`
FOREIGN KEY (`QuestionID` )
REFERENCES `assessmentbookdb`.`Question` (`QuestionID` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
Message Log:
ERROR 1005: Can't create table 'assessmentbookdb.mcqs' (errno: 121)
SQL Statement:
CREATE TABLE `assessmentbookdb`.`MCQs` (
`id` INT NOT NULL AUTO_INCREMENT ,
`MCQAnswer` VARCHAR(200) NOT NULL ,
`QuestionID` INT NOT NULL ,
PRIMARY KEY (`id`) ,
INDEX `QuestionID` (`QuestionID` ASC) ,
CONSTRAINT `QuestionID`
FOREIGN KEY (`QuestionID` )
REFERENCES `assessmentbookdb`.`Question` (`QuestionID` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB

Double-check that:
The key's name is unique
The two keys you're coupling have the exact same datatype (here: INT NOT NULL), even signedness
The referencing fields actually exist

based on googling i would assume that you have a constraint that exists with the same name that you try to add a constraint with. It might be that you didnt delete an old constraint from the old version of the table or something.

table creation failed because a foreign key constraint was not correctly formed
Somehow your foreign key is not correct. This can be if the table you are refering does not exist yet.

Take a look Here and try to not give a name to your constraint.

http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
InnoDB supports foreign keys, which let you cross-reference related data across tables, and foreign key constraints, which help keep this spread-out data consistent. The syntax for an InnoDB foreign key constraint definition in the CREATE TABLE or ALTER TABLE statement looks like this:
[CONSTRAINT [symbol]] FOREIGN KEY
[index_name] (index_col_name, ...)
REFERENCES tbl_name (index_col_name,...)
[ON DELETE reference_option]
[ON UPDATE reference_option]
reference_option:
RESTRICT | CASCADE | SET NULL | NO ACTION

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

mysql error 150 from referencing same foreign key column in two tables

I have looked through quite a few posts but havent found the solution for my problem. My suspicion is the error stems from me trying to use a single column to reference the same primary key column in two different tables. Specifically the bid table has the foreign key simulation_id that is also present in the bidder and item_round_status tables. the bid table references the foreign keys of both of these tables but I would like to use only one simulation_id column in the table. Is this the source of the Error 150 problem?
-- -----------------------------------------------------
-- Table `kffg_simulations`.`item_round_status`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `kffg_simulations`.`item_round_status` (
`simulation_id` INT NOT NULL ,
`round` INT NOT NULL ,
`clock_item_id` INT NOT NULL ,
`posted_price` BIGINT NOT NULL ,
`clock_price` BIGINT NOT NULL ,
PRIMARY KEY (`simulation_id`, `round`, `clock_item_id`) ,
INDEX `fk_item_round_status_clock_item1_idx` (`clock_item_id` ASC) ,
INDEX `fk_item_round_status_simulation1_idx` (`simulation_id` ASC) ,
CONSTRAINT `fk_item_round_status_clock_item1`
FOREIGN KEY (`clock_item_id`)
REFERENCES `kffg_simulations`.`clock_item` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_item_round_status_simulation1`
FOREIGN KEY (`simulation_id`)
REFERENCES `kffg_simulations`.`simulation` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `kffg_simulations`.`bidder`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `kffg_simulations`.`bidder` (
`simulation_id` INT NOT NULL ,
`idx` INT NOT NULL ,
`bidder_strategy_id` INT NOT NULL ,
`budget` BIGINT NOT NULL ,
PRIMARY KEY (`simulation_id`, `idx`) ,
INDEX `fk_bidder_simulation1_idx` (`simulation_id` ASC) ,
INDEX `fk_bidder_bidder_strategy1_idx` (`bidder_strategy_id` ASC) ,
CONSTRAINT `fk_bidder_simulation1`
FOREIGN KEY (`simulation_id`)
REFERENCES `kffg_simulations`.`simulation` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_bidder_bidder_strategy1`
FOREIGN KEY (`bidder_strategy_id`)
REFERENCES `kffg_simulations`.`bidder_strategy` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `kffg_simulations`.`bid_type`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `kffg_simulations`.`bid_type` (
`id` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(45) NOT NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `kffg_simulations`.`bid_status`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `kffg_simulations`.`bid_status` (
`id` INT NOT NULL AUTO_INCREMENT ,
`description` VARCHAR(45) NOT NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `kffg_simulations`.`bid`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `kffg_simulations`.`bid` (
`simulation_id` INT NOT NULL ,
`item_round_status_round` INT NOT NULL ,
`clock_item_id` INT NOT NULL ,
`bidder_idx` INT NOT NULL ,
`quantity` INT NOT NULL ,
`price` INT NOT NULL ,
`bid_type_id` INT NOT NULL ,
`switch_to_pea_category_id` INT NOT NULL ,
`backstop` BIGINT NULL ,
`bid_status_id` INT NOT NULL ,
`processed_demand` INT NOT NULL ,
PRIMARY KEY (`simulation_id`, `item_round_status_round`, `clock_item_id`, `bidder_idx`, `quantity`) ,
INDEX `fk_bid_item_round_status1_idx` (`simulation_id` ASC, `item_round_status_round` ASC, `clock_item_id` ASC) ,
INDEX `fk_bid_bidder1_idx` (`simulation_id` ASC, `bidder_idx` ASC) ,
INDEX `fk_bid_bid_type1_idx` (`bid_type_id` ASC) ,
INDEX `fk_bid_pea_category1_idx` (`switch_to_pea_category_id` ASC) ,
INDEX `fk_bid_bid_status1_idx` (`bid_status_id` ASC) ,
CONSTRAINT `fk_bid_item_round_status1`
FOREIGN KEY (`simulation_id` , `item_round_status_round` , `clock_item_id`)
REFERENCES `kffg_simulations`.`item_round_status` (`simulation_id` , `round` , `clock_item_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_bid_bidder1`
FOREIGN KEY (`bidder_idx` , `simulation_id`)
REFERENCES `kffg_simulations`.`bidder` (`idx` , `simulation_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_bid_bid_type1`
FOREIGN KEY (`bid_type_id`)
REFERENCES `kffg_simulations`.`bid_type` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_bid_pea_category1`
FOREIGN KEY (`switch_to_pea_category_id`)
REFERENCES `kffg_simulations`.`pea_category` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_bid_bid_status1`
FOREIGN KEY (`bid_status_id`)
REFERENCES `kffg_simulations`.`bid_status` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
Updated to show error message:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
170604 21:52:27 Error in foreign key constraint of table kffg_simulations/bid:
FOREIGN KEY (`simulation_id` , `item_round_status_round` , `clock_item_id`)
REFERENCES `kffg_simulations`.`item_round_status` (`simulation_id` , `round` , `clock_item_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_bid_bidder1`
FOREIGN KEY (`bidder_idx` , `simulation_id`)
REFERENCES `kffg_simulations`.`bidder` (`idx` , `simulation_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_bid_bid_type1`
FOREIGN KEY (`bid_type_id`)
REFERENCES `kffg_simulations`.`bid_type` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_bid_pea_category1`
FOREIGN KEY (`switch_to_pea_category_id`)
REFERENCES `kffg_simulations`.`pea_category` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_bid_bid_status1`
FOREIGN KEY (`bid_status_id`)
REFERENCES `kffg_simulations`.`bid_status` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB:
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
Also updated with uml diagram:
Foreign Key Usage and Error Information gives info on FKs (foreign keys).
you can obtain a detailed explanation of the most recent InnoDB foreign key error by checking the output of SHOW ENGINE INNODB STATUS.
InnoDB permits a foreign key to reference any index column or group of columns. However, in the referenced table, there must be an index where the referenced columns are listed as the first columns in the same order.
In bid:
FOREIGN KEY (`bidder_idx` , `simulation_id`)
REFERENCES `kffg_simulations`.`bidder` (`idx` , `simulation_id`)
The "referenced table" here is bidder, the "referenced columns" list is (idx , simulation_id).
Cannot find an index in the referenced table where the
referenced columns appear as the first columns,
Sure enough, in bidder the closest we find is:
PRIMARY KEY (`simulation_id`, `idx`) ,
which implicitly declares a default unique not null index, but like all the other indexes doesn't start with the FK's column list.
Philipxy thank you for your help on this problem. You were correct in the comment that the foreign key for bidder was wrong. For some reason mysql workbench generated the columns in the code in the wrong order. The code provided by mysqlworkbench is below:
CONSTRAINT `fk_bid_bidder1`
FOREIGN KEY (`bidder_idx` , `simulation_id`)
REFERENCES `kffg_simulations`.`bidder` (`idx` , `simulation_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
And the following code works properly:
CONSTRAINT `fk_assignment_bidder1`
FOREIGN KEY (`bidder_simulation_id` , `bidder_idx`)
REFERENCES `kffg_simulations`.`bidder` (`simulation_id` , `idx`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
As far as I can tell I had the indexing setup properly but the code was generate in the wrong order.
(I used mysql workbench forward engineer to generate the sql script. I used the gui to create the relationships between the bid table, bidder, and item_round_status. Since both of those tables have simulationid as pk it duplicated that column. When I manually adjusted the foreign key for bidder to reference the simulationid column generated for item_round_status it changed the indices related to that foreign key. I manually changed them to the proper indices but it seems to ignore my changes when generating the script causing the error.)

Error 1822: Failed to add the foreign key constaint. Missing index for constraint

I found some threads about the error. But all the solutions does not work for me.
My system already had the following tables:
CREATE TABLE `bdo2_agencia` (
`cod_uf` char(2) NOT NULL,
`cod_agencia` char(9) NOT NULL,
`nome` varchar(100) NOT NULL,
PRIMARY KEY (`cod_uf`,`cod_agencia`),
KEY `fk_agencia_2_uf_idx` (`cod_uf`),
CONSTRAINT `fk_agencia_2_uf` FOREIGN KEY (`cod_uf`) REFERENCES `bdo2_uf` (`cod_uf`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `bdo2_login` (
`login` char(30) NOT NULL,
`ativo` tinyint(1) DEFAULT '1' COMMENT 'informa se o login está ativo',
PRIMARY KEY (`login`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I tried to create another table between them, defining a relationship N:M
CREATE TABLE IF NOT EXISTS `bdo2`.`bdo2_login_agencia` (
`cod_uf` CHAR(2) NOT NULL,
`cod_agencia` CHAR(9) NOT NULL,
`login` CHAR(30) NOT NULL,
PRIMARY KEY (`cod_uf`, `cod_agencia`, `login`),
INDEX `fk_login_2_login_agencia_idx` (`login` ASC),
INDEX `fk_agencia_2_login_agencia_idx` (`cod_uf` ASC, `cod_agencia` ASC),
CONSTRAINT `fk_agencia_2_login_agencia`
FOREIGN KEY (`cod_uf` , `cod_agencia`)
REFERENCES `bdo2`.`bdo2_agencia` (`cod_uf` , `cod_agencia`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_login_2_login_agencia`
FOREIGN KEY (`login`) REFERENCES `bdo2`.`bdo2_login` (`login`) ON DELETE NO ACTION ON UPDATE NO ACTION)
ENGINE = InnoDB;
but I received the following error:
Error Code: 1215. Cannot add foreign key constraint
With the command
SHOW ENGINE innodb STATUS
I got the following message:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
2016-03-22 10:14:05 7fe09c49f700 Error in foreign key constraint of table bdo2/bdo2_login_agencia:
FOREIGN KEY (`cod_uf` , `cod_agencia`)
REFERENCES `bdo2`.`bdo2_agencia` (`cod_uf` , `cod_agencia`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_login_2_login_agencia`
FOREIGN KEY (`login`) REFERENCES `bdo2`.`bdo2_login` (`login`)
ON DELETE NO ACTION ON UPDATE NO ACTION)
ENGINE = InnoDB:
Cannot find an index in the referenced table where the referenced
columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
So I created the table without the constraints and I tried to create the constraints individually
ALTER TABLE `bdo2`.`bdo2_login_agencia`
ADD INDEX `fk_agencia_2_login_agencia_idx` (`cod_uf` ASC, `cod_agencia` ASC),
ADD INDEX `fk_login_2_login_agencia_idx` (`login` ASC);
ALTER TABLE `bdo2`.`bdo2_login_agencia`
ADD CONSTRAINT `fk_agencia_2_login_agencia`
FOREIGN KEY (`cod_uf` , `cod_agencia`)
REFERENCES `bdo2`.`bdo2_agencia` (`cod_uf` , `cod_agencia`)
ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_login_2_login_agencia`
FOREIGN KEY (`login`)
REFERENCES `bdo2`.`bdo2_login` (`login`)
ON DELETE NO ACTION ON UPDATE NO ACTION;
but received the following error:
ERROR 1822: Failed to add the foreign key constaint. Missing index for constraint 'fk_agencia_2_login_agencia' in the referenced table 'bdo2_agencia'
If index exists, why returns this message?
It would be a bug of version? I tested in two servers (versions 5.6.23 and 5.6.29) on Linux, both presented the same problem.
The problem was in COLLATION. I found that bdo2_login and bdo2_agencia tables were with CHARSET = utf8, but did not realize that the Workbench put the new table as latin1. It was enough to hit the CHARSET and COLLATION that solved.
I had the same problem in another creation of FK and the problem was COLLATION only the columns. The table had the PK had COLLATION utf8 and the column was created as FK as latin1. It was enough to hit the COLLATION that the problem was solved.

Disable foreign key check in insert operation in MySql

I have a table which is using to map two primary keys of other two tables. i make these two fields as foreign keys. The mapping table has no primary key When i am trying to insert 2 value which already in that two tables, i am getting Cannot add or update a child row: a foreign key constraint fails error.
How can i solve this issue ?
My Table is like this :
CREATE TABLE IF NOT EXISTS fuse_package_component_members
( component_id int(11) NOT NULL,
member_type int(11) NOT NULL,
member_id int(11) NOT NULL,
active_date date NOT NULL,
inactive_date date NOT NULL,
KEY component_id (component_id),
KEY member_id (member_id) )
ENGINE=InnoDB DEFAULT CHARSET=latin1
ALTER TABLE fuse_package_component_members
ADD CONSTRAINT comp_id_fk
FOREIGN KEY (component_id) REFERENCES fuse_component_definition (component_id) ON UPDATE NO ACTION,
ADD CONSTRAINT ele_id_fk
FOREIGN KEY (member_id) REFERENCES fuse_product_element (element_id)
ON DELETE NO ACTION ON UPDATE NO ACTION;
SET foreign_key_checks = 0;
UPDATE ...
SET foreign_key_checks = 1;
https://dev.mysql.com/doc/refman/5.5/en/create-table-foreign-keys.html
Remove the foreign key constraint from the table, insert the data and re-enforce the constraint..
ALTER TABLE table_name
DROP FOREIGN KEY constraint_name
if you want to check the constraint name, just run the query
show create table table_name
It will show you the whole schema along with all the imposed constraints...
Add the constraints again
A good link to follow -> http://www.w3schools.com/sql/sql_foreignkey.asp

SQL : ERROR 1005: Can't create table 'obl2.itemsubjects' (errno: 121)

I have the following tables:
CREATE TABLE `OBL2`.`item` (
`itemID` INT NOT NULL AUTO_INCREMENT ,
`itemName` VARCHAR(45) NOT NULL ,
PRIMARY KEY (`itemID`) ,
INDEX `itemName` (`itemName` ASC) );
CREATE TABLE `OBL2`.`subject` (
`subjectID` INT NOT NULL ,
`subjectName` VARCHAR(45) NOT NULL ,
PRIMARY KEY (`subjectID`) );
Now since the connection is many to many, each item can have many subject and each subject can be related to many items - I'd like to set a connection table.
This is my code:
CREATE TABLE `OBL2`.`itemsubjects` (
`itemID` INT NOT NULL ,
`subjectID` INT NOT NULL ,
PRIMARY KEY (`itemID`, `subjectID`) ,
INDEX `itemID_idx` (`itemID` ASC) ,
INDEX `subjectID_idx` (`subjectID` ASC) ,
CONSTRAINT `itemID`
FOREIGN KEY (`itemID` )
REFERENCES `OBL2`.`item` (`itemID` )
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `subjectID`
FOREIGN KEY (`subjectID` )
REFERENCES `OBL2`.`subject` (`subjectID` )
ON DELETE CASCADE
ON UPDATE CASCADE);
but for some reason the code of the 3rd table is not being accepted.
I get an error message:
ERROR 1005: Can't create table 'obl2.itemsubjects' (errno: 121)
I've read about the error on the internet and it says it's a known issue of MYSQL yet there are no solutions.
Any thoughts?
The MySQL docs say in FOREIGN KEY Constraints (emphasis mine):
If the CONSTRAINT symbol clause is given, the symbol value must be unique in the database. If the clause is not given, InnoDB creates the name automatically.
So, the reason that the itemsubject table creation failed, was that you had another (foreign key) constraint, named itemID, or one named subjectID in some other table of the database.
It's good to have a naming conevntion that is standard across the database. Just as you have ColumnName_idx for indices, you can use ReferencedTable_ReferencingTable_FK for foreign key constraints:
CREATE TABLE OBL2.itemsubjects (
itemID INT NOT NULL ,
subjectID INT NOT NULL ,
PRIMARY KEY
(itemID, subjectID) ,
INDEX itemID_idx -- I like these
(itemID ASC) ,
INDEX subjectID_idx -- two
(subjectID ASC) ,
CONSTRAINT item_itemsubject_FK -- what I propose, here
FOREIGN KEY (itemID)
REFERENCES OBL2.item (itemID)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT subject_itemsubject_FK -- and here
FOREIGN KEY (subjectID)
REFERENCES OBL2.subject (subjectID)
ON DELETE CASCADE
ON UPDATE CASCADE
);