MySQL fk reference back to table...unable to insert new row - mysql

thanks for taking time to look at my thread.
I'm 'trying to' create a MySQL table for item categories with a column for the parent category in the table. I linked it back to the table as a fk and intend to insert (0) into the column value for items that have no parents.
Here is the table definition:
-- -----------------------------------------------------
-- Table `mydb`.`itemCategories`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`itemCategories` (
`itecat_id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`category` VARCHAR(60) NOT NULL ,
`parentCat` INT UNSIGNED NOT NULL ,
PRIMARY KEY (`itecat_id`) ,
UNIQUE INDEX `uniqueCat` (`category` ASC) ,
INDEX `fk_itemCategories_itemCategories1` (`parentCat` ASC) ,
CONSTRAINT `fk_itemCategories_itemCategories1`
FOREIGN KEY (`parentCat` )
REFERENCES `mydb`.`itemCategories` (`itecat_id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
When I try to insert a new row, it gives the following error:
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`mydb`.`itemCategories`, CONSTRAINT `fk_itemCategories_itemCategories1` FOREIGN KEY (`parentCat`) REFERENCES `itemCategories` (`itecat_id`) ON DELETE NO ACTION)
Any help on how to fix this, or a better way to do it, would be very much appreciated.
Thanks!

0 is a value! You should use NULL as the "empty field".

Related

MySQL Workbench reports ERROR 1822: Failed to add the foreign key constraint. Missing index for constraint

I'm creating a mysql db based from an EER model sql script and when trying to do the conversion (all in MySQL Workbench), I'm getting the error above. My goal is to reference the adoption_entity_id on the adoption_entity table from 2 columns in attachment table (sent_from and from_to).
I have 2 tables, one of which is the attachment:
-- -----------------------------------------------------
-- Table `afth_db`.`attachment`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `afth_db`.`attachment` ;
CREATE TABLE IF NOT EXISTS `afth_db`.`attachment` (
`attachment_id` BIGINT NOT NULL,
`sent_from` INT NULL,
`sent_to` INT NULL,
`attachment_description` LONGTEXT NULL,
`attachment_uploaded` DATETIME NULL,
`attachment_uploaded_by` VARCHAR(255) NULL,
`adoption_case_num` BIGINT NOT NULL,
PRIMARY KEY (`attachment_id`),
INDEX `fk_attachment_adoption_case1_idx` (`adoption_case_num` ASC) VISIBLE,
UNIQUE INDEX `attachment_id_UNIQUE` (`attachment_id` ASC) VISIBLE,
UNIQUE INDEX `adoption_case_num_UNIQUE` (`adoption_case_num` ASC) VISIBLE,
INDEX `fk_attachment_adoption_entity1_idx` (`sent_from` ASC, `sent_to` ASC) VISIBLE,
UNIQUE INDEX `sent_to_UNIQUE` (`sent_to` ASC) VISIBLE,
UNIQUE INDEX `sent_from_UNIQUE` (`sent_from` ASC) VISIBLE,
CONSTRAINT `fk_attachment_adoption_case1`
FOREIGN KEY (`adoption_case_num`)
REFERENCES `afth_db`.`adoption_case` (`case_num`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_attachment_adoption_entity1`
FOREIGN KEY (`sent_from` , `sent_to`)
REFERENCES `afth_db`.`adoption_entity` (`adoption_entity_id` , `adoption_entity_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
and the other is the adoption entity:
-- -----------------------------------------------------
-- Table `afth_db`.`adoption_entity`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `afth_db`.`adoption_entity` (
`adoption_entity_id` INT NOT NULL,
`adoption_entity_type` VARCHAR(255) NULL,
PRIMARY KEY (`adoption_entity_id`),
UNIQUE INDEX `adoption_entity_id_UNIQUE` (`adoption_entity_id` ASC) VISIBLE)
ENGINE = InnoDB
The error states in detail:
Operation failed: There was an error while applying the SQL script to the database.
ERROR 1822: Failed to add the foreign key constraint. Missing index for constraint 'fk_attachment_adoption_entity1' in the referenced table 'adoption_entity'
I'm not sure why its been giving me this issue though. I've tried several solutions from setting type to 'unique index', 'index' for fk_attachment_adoption_entity1 along with the other columns involved, but I can't seem to be able to get rid of the error. I've also tried deleting and recreating the 1-1 relationship but that didnt help either. Can anyone tell me if I'm doing something wrong here on the EER model design?
You are trying to create one foreign key reference, which spans over the two columns sent_from and sent_to to single rows in the adoption_entity table. That's not what you want. You want to create two separate foreign key references instead for the individual columns sent_from and sent_to. So the constraint parts should look like this:
CONSTRAINT `fk_attachment_adoption_entity_from`
FOREIGN KEY (`sent_from`)
REFERENCES `afth_db`.`adoption_entity` (`adoption_entity_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION),
CONSTRAINT `fk_attachment_adoption_entity_to`
FOREIGN KEY (`sent_to`)
REFERENCES `afth_db`.`adoption_entity` (`adoption_entity_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)

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

Four foreign keys two per table cannot be referenced to a single primary key in main table

Good day
I'm trying to solve an issue with foreign key relationship between three tables. Basically I have two secondary tables, each one has two foreign keys and each foreign key is referenced to a single primary key in the third table.
This same issue happens in a much larger database, however due to its complexity, size and possible copyright issues. I had no choice but to isolate the problem and create a replica that would result in the same issue. However if you must know, the same two tables that reference the main table People are just two in a universe of dozens of the same kind in the database in question.
My hope is that someone can point the problem and maybe provide a solution that wouldn't effect much of the current structure, so that I can apply it myself, probably to all other tables because from what I see of the database diagram, its likely they will all suffer from the same problem. Database authorship is not mine, which only adds to one's confusion when looking at the diagram.
The SQL create script:
CREATE SCHEMA IF NOT EXISTS `sampleBD` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci ;
USE `sampleBD` ;
-- -----------------------------------------------------
-- Table `sampleBD`.`People`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `sampleBD`.`People` (
`PeopleID` INT NOT NULL AUTO_INCREMENT ,
`Name` VARCHAR(200) NOT NULL ,
`EntryDate` DATETIME NULL ,
`EntryBy` INT NULL ,
PRIMARY KEY (`PeopleID`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `sampleBD`.`PeopleNumberId`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `sampleBD`.`PeopleNumberId` (
`PeopleNumberIdID` INT NOT NULL AUTO_INCREMENT ,
`PeopleID` INT NOT NULL ,
`NumberId` INT(11) NOT NULL ,
`EntryDate` DATETIME NULL ,
`EntryBy` INT NULL ,
PRIMARY KEY (`PeopleNumberIdID`) ,
INDEX `PeopleID` (`PeopleID` ASC) ,
INDEX `EntryBy` (`EntryBy` ASC) ,
CONSTRAINT `PeopleID`
FOREIGN KEY (`PeopleID` )
REFERENCES `sampleBD`.`People` (`PeopleID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `EntryBy`
FOREIGN KEY (`EntryBy` )
REFERENCES `sampleBD`.`People` (`PeopleID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `sampleBD`.`PeopleCbi`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `sampleBD`.`PeopleCbi` (
`PeopleCbiID` INT NOT NULL AUTO_INCREMENT ,
`PeopleID` INT NOT NULL ,
`Cbi` INT NOT NULL ,
`EntryDate` DATETIME NULL ,
`EntryBy` INT NULL ,
PRIMARY KEY (`PeopleCbiID`) ,
INDEX `PessoaID` (`PeopleID` ASC) ,
INDEX `EntryBy` (`EntryBy` ASC) ,
CONSTRAINT `PessoaID`
FOREIGN KEY (`PeopleID` )
REFERENCES `sampleBD`.`People` (`PeopleID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `EntryBy`
FOREIGN KEY (`EntryBy` )
REFERENCES `sampleBD`.`People` (`PeopleID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
The script is able to create the first and second tables, however when it reaches the third table it returns an error code.
Error Code: 1005. Can't create table 'samplebd.peoplecbi' (errno: 121)
It's a foreign key problem, but I'm not sure how it could be fixed without altering the current structure of the table or tables involved.
Thanks for the help.
This looks like a name conflict between foreign key constraint names. Constraint names must be unique in a database, like table names are.
So just choose another name for the constraint EntryBy in the 3rd table. It will not affect any of the functionality you have.

MySQL Triggers - Implementation Issue

I am developing a MySQL database using Workbench. I want two send two fields from a newly created record to another table. I would then like to update the original table with newly created data from the second table. I was looking to implement this with triggers, unless there is a better way of course :) My attempt was a fail when I went to upload it(see below)
Specifically, I would like tc_Event to send the ID & tc_EventTags_ID to tc_EventTags to fill in tc_Tag_ID & tc_Event_ID. Afterwards I want the ID of tc_EventTags sent back to tc_Event to the tc_EventTags_ID field.
Thanks for any help.
-- -----------------------------------------------------
-- Table `mcontest`.`tc_EventTags`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mcontest`.`tc_EventTags` (
`ID` INT NOT NULL AUTO_INCREMENT ,
`tc_Tag_ID` INT NOT NULL ,
`tc_Event_ID` INT NOT NULL ,
PRIMARY KEY (`ID`) ,
INDEX `fk_tc_EventTags_tc_Tag1` (`tc_Tag_ID` ASC) ,
INDEX `fk_tc_EventTags_tc_Event1` (`tc_Event_ID` ASC) ,
CONSTRAINT `fk_tc_EventTags_tc_Tag1`
FOREIGN KEY (`tc_Tag_ID` )
REFERENCES `mcontest`.`tc_Tag` (`ID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_tc_EventTags_tc_Event1`
FOREIGN KEY (`tc_Event_ID` )
REFERENCES `mcontest`.`tc_Event` (`ID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = MyISAM;
-- -----------------------------------------------------
-- Table `mcontest`.`tc_Event`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mcontest`.`tc_Event` (
`ID` INT NOT NULL AUTO_INCREMENT ,
`date` DATE NOT NULL ,
`time` TIME NOT NULL ,
`location` VARCHAR(45) NOT NULL ,
`description` VARCHAR(45) NOT NULL ,
`tc_EventTags_ID` INT NULL ,
`tc_Orgs_ID` INT NOT NULL ,
`tc_PersonEvent_ID` INT NOT NULL ,
PRIMARY KEY (`ID`) ,
INDEX `fk_tc_Event_tc_EventTags1` (`tc_EventTags_ID` ASC) ,
INDEX `fk_tc_Event_tc_Orgs1` (`tc_Orgs_ID` ASC) ,
INDEX `fk_tc_Event_tc_PersonEvent1` (`tc_PersonEvent_ID` ASC) ,
CONSTRAINT `fk_tc_Event_tc_EventTags1`
FOREIGN KEY (`tc_EventTags_ID` )
REFERENCES `mcontest`.`tc_EventTags` (`ID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_tc_Event_tc_Orgs1`
FOREIGN KEY (`tc_Orgs_ID` )
REFERENCES `mcontest`.`tc_Orgs` (`ID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_tc_Event_tc_PersonEvent1`
FOREIGN KEY (`tc_PersonEvent_ID` )
REFERENCES `mcontest`.`tc_PersonEvent` (`ID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = MyISAM;
USE `mcontest`;
DELIMITER $$
USE `mcontest`$$
CREATE TRIGGER eventTag_Trigger
AFTER insert ON tc_Event
FOR EACH ROW BEGIN
INSERT INTO tc_EventTags values('',NEW.tc_Event_ID);
END;
END$$
DELIMITER ;
SET SQL_MODE=#OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=#OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=#OLD_UNIQUE_CHECKS;
Why have put a tc_EventTags_ID in table tc_Event? What is the logic behind that?
I mean that the relationship between the 2 tables would be (I guess): 1 Event - many EventTags. This is already achieved by the tc_EventTags.tc_Event_ID which is a Foreign Key to tc_Event.
To answer your question:
As it is now, the Trigger tries for every row inserted in table Event, to add a row in table EventTag. But it will fail for 2 reasons:
EventTag has 2 Constraints (Foreign keys) which have to be fulfilled for the triggered insert to succeed. So, tc_Event_ID is ok but tc_Tag_ID has to be NOT NULL and reference the Tag table but the value you supply, '', probably is not in table Tag.
EDIT: the value you supply, '', is also a CHAR while it should be INT.
But trigger will probably not be started at all, since every time you insert a row in table Event, those constraints have to be fulfilled and one of them is the tc_EventTags_ID which references EventTag table. But EventTag table is empty. Do you see the circular logic here?

SQL - error code 1005 with error number 121

I'm running the following MySQL query (trimmed down), generated automatically by MySQL Workbench and I get the following error:
Error Code: 1005
Can't create table 'regula.reservation' (errno: 121)
I'm not very proficient with databases and this error is not very informative.
What is the problem here?
-- -----------------------------------------------------
-- Table `regula`.`Users`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `regula`.`Users` ;
CREATE TABLE IF NOT EXISTS `regula`.`Users` (
`idUsers` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`name` TEXT NOT NULL ,
`type` TEXT NOT NULL ,
`pwd` TEXT NOT NULL ,
PRIMARY KEY (`idUsers`) ,
UNIQUE INDEX `idUsers_UNIQUE` (`idUsers` ASC) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `regula`.`Projects`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `regula`.`Projects` ;
CREATE TABLE IF NOT EXISTS `regula`.`Projects` (
`idProjects` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`ownerId` INT UNSIGNED NOT NULL ,
`name` TEXT NOT NULL ,
`date` DATE NOT NULL ,
`time` TIME NOT NULL ,
`place` TEXT NOT NULL ,
`itemType` INT NOT NULL ,
PRIMARY KEY (`idProjects`) ,
UNIQUE INDEX `idProjects_UNIQUE` (`idProjects` ASC) ,
INDEX `ownerId` (`ownerId` ASC) ,
CONSTRAINT `ownerId`
FOREIGN KEY (`ownerId` )
REFERENCES `regula`.`Users` (`idUsers` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `regula`.`ItemTypes`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `regula`.`ItemTypes` ;
CREATE TABLE IF NOT EXISTS `regula`.`ItemTypes` (
`idItemTypes` INT UNSIGNED NOT NULL ,
`prjId` INT UNSIGNED NOT NULL ,
`parentId` INT UNSIGNED NULL DEFAULT NULL ,
`name` TEXT NOT NULL ,
PRIMARY KEY (`idItemTypes`) ,
INDEX `prjId` (`prjId` ASC) ,
INDEX `parentId` (`parentId` ASC) ,
CONSTRAINT `prjId`
FOREIGN KEY (`prjId` )
REFERENCES `regula`.`Projects` (`idProjects` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `parentId`
FOREIGN KEY (`parentId` )
REFERENCES `regula`.`ItemTypes` (`idItemTypes` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `regula`.`Reservation`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `regula`.`Reservation` ;
CREATE TABLE IF NOT EXISTS `regula`.`Reservation` (
`idReservation` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`prjId` INT UNSIGNED NOT NULL ,
`itemTypeId` INT UNSIGNED NOT NULL ,
`userId` INT UNSIGNED NOT NULL ,
PRIMARY KEY (`idReservation`) ,
INDEX `prjId` (`prjId` ASC) ,
INDEX `itemTypeId` (`itemTypeId` ASC) ,
INDEX `userId` (`userId` ASC) ,
CONSTRAINT `prjId`
FOREIGN KEY (`prjId` )
REFERENCES `regula`.`Projects` (`idProjects` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `itemTypeId`
FOREIGN KEY (`itemTypeId` )
REFERENCES `regula`.`ItemTypes` (`idItemTypes` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `userId`
FOREIGN KEY (`userId` )
REFERENCES `regula`.`Users` (`idUsers` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
Error 121 means that there is a foreign key constraint error. Since you're using InnoDB, you can use SHOW ENGINE INNODB STATUS after running the failed query to get an explanation in the LATEST FOREIGN KEY ERROR section. Having run your SQL myself, I get this:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
101210 14:55:50 Error in foreign key constraint creation for table `regula`.`Reservation`.
A foreign key constraint of name `regula`.`prjId`
already exists. (Note that internally InnoDB adds 'databasename'
in front of the user-defined constraint name.)
Note that InnoDB's FOREIGN KEY system tables store
constraint names as case-insensitive, with the
MySQL standard latin1_swedish_ci collation. If you
create tables or databases whose names differ only in
the character case, then collisions in constraint
names can occur. Workaround: name your constraints
explicitly with unique names.
Basically, you need to give your prjId constraint name a unique name in the last table. Constraint/foreign key names are global to a database, so they cannot be reused in different tables. Just change the last
CONSTRAINT `prjId`
to
CONSTRAINT `prjId2`
The error code 121 comes when you try to map the foreign key.
Basically it comes when your foreign key name already exists in the database.
For example:
ALTER TABLE `photokiosk`.`kiosk_event`
ADD CONSTRAINT `event_booking_id`
FOREIGN KEY `event_booking_id` (`event_booking_id`)
REFERENCES `event_booking` (`event_booking_id`)
If foreign key with the name event_booking_id is already mapped with the other table.
To get rid of this issue, please change the foreign key name, not the column name.
You will get this error message if you try to use a constraint name which already exists in the table.
Here 'prjId' already exists in table regula.ItemTypes. So, you can't use the same constraint name on table 'regula.reservation' again.