I'm working on my first MySQL database for an assignment at my university. Unfortunately I've been stuck for a while trying to create the actual tables with foreign keys between them.
This is the error that the MySQL Workbench forward engineering wizard gives:
Executing SQL script in server
ERROR: Error 1005: Can't create table 'test.fremført' (errno: 150)
CREATE TABLE IF NOT EXISTS `Fremført` (
`Plate` VARCHAR(20) NOT NULL ,
`Verk` VARCHAR(45) NOT NULL ,
`Artist` VARCHAR(45) NOT NULL ,
`Dato` DATE NULL ,
PRIMARY KEY (`Plate`, `Verk`, `Artist`) ,
INDEX `Fremført->Artist_idx` (`Artist` ASC) ,
INDEX `Fremført->Spor_idx` (`Plate` ASC, `Verk` ASC) ,
CONSTRAINT `Fremført->Artist`
FOREIGN KEY (`Artist` )
REFERENCES `Artist` (`ArtistNavn` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `Fremført->Spor`
FOREIGN KEY (`Plate` , `Verk` )
REFERENCES `Spor` (`Verk` , `Verk` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
Does anyone know what's wrong with the above script, and if so have a solution?
Thanks!
edit:
This is the requested spor query
DROP TABLE IF EXISTS `Spor` ;
CREATE TABLE IF NOT EXISTS `Spor` (
`Plate` VARCHAR(45) NOT NULL ,
`Verk` VARCHAR(45) NOT NULL ,
`Spilletid` DECIMAL(3,2) NULL ,
PRIMARY KEY (`Plate`, `Verk`) ,
INDEX `Plate_idx` (`Plate` ASC) ,
CONSTRAINT `Plate`
FOREIGN KEY (`Plate` )
REFERENCES `Plate` (`KatalogNr` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
DROP TABLE IF EXISTS `Artist` ;
CREATE TABLE IF NOT EXISTS `Artist` (
`ArtistNavn` VARCHAR(30) NOT NULL ,
`Artistcol` VARCHAR(45) NULL ,
PRIMARY KEY (`ArtistNavn`) )
ENGINE = InnoDB;
errno150 is very often related to a mismatch between the data types of the primary and related column. They must match exactly, including character length.
I see a data type mismatch between Fremført.artist (VARCHAR(45)) and Artist.ArtistNavn (VARCHAR(30)). These must be the same for the FOREIGN KEY constraint to succeed.
CREATE TABLE IF NOT EXISTS `Fremført` (
`Plate` VARCHAR(20) NOT NULL ,
`Verk` VARCHAR(45) NOT NULL ,
/* Must match the primary table VARCHAR(30) */
`Artist` VARCHAR(30) NOT NULL ,
`Dato` DATE NULL ,
PRIMARY KEY (`Plate`, `Verk`, `Artist`) ,
INDEX `Fremført->Artist_idx` (`Artist` ASC) ,
INDEX `Fremført->Spor_idx` (`Plate` ASC, `Verk` ASC) ,
CONSTRAINT `Fremført->Artist`
FOREIGN KEY (`Artist` )
REFERENCES `Artist` (`ArtistNavn` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `Fremført->Spor`
FOREIGN KEY (`Plate` , `Verk` )
/* Was this intentional, rather than (`Plate`, `Verk`)? */
/* If not, you must also match the data type of `Plate` VARCHAR(20) to that of Spor.Plate VARCHAR(45) */
REFERENCES `Spor` (`Verk` , `Verk` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
As noted above, if the constraint Fremført->Spor was intended to reference Spor (Plate , Verk ) instead of Spor (Verk , Verk ) as you have defined it, then you will also encounter an err150 due to the type mismatch between Spor.Plate and Fremført.Plate. Change Fremført.Plate to VARCHAR(45).
Error 150 is a foreign key constraint issue. I would suspect that one of the two FK's you have have an issue.
See: http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
(errno: 150) that error mean that the FK failed so the create table too....
Please review your FK.
Did you already created it? (the table with the PK pointing to this one)
Did your spell it right?
Is it the same data type that the PK?
Related
I have the following schema. How do I ensure that all values in child are unique for a given child.group_id, child.type, and parent.status? Please note the 1-to-1 relationship between parent and child. If parent and child was one table, a simple UNIQUE index would work, however, I wish to keep the two tables separate. Ideally, stored procedures wouldn't be used, however, I am open to them if necessary. I am using the latest version of MySQL. Thank you
CREATE TABLE IF NOT EXISTS group (
id INT NOT NULL AUTO_INCREMENT ,
moreData VARCHAR(45) NULL ,
PRIMARY KEY (id) )
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS parent (
id INT NOT NULL AUTO_INCREMENT ,
status VARCHAR(45) NOT NULL ,
moreData VARCHAR(45) NULL ,
PRIMARY KEY (id) )
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS child (
parent_id INT NOT NULL ,
group_id INT NOT NULL ,
type INT NOT NULL ,
moreData VARCHAR(45) NULL ,
PRIMARY KEY (parent_id) ,
INDEX fk_child_group1_idx (group_id ASC) ,
CONSTRAINT fk_child_parent
FOREIGN KEY (parent_id )
REFERENCES parent (id )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT fk_child_group1
FOREIGN KEY (group_id )
REFERENCES group (id )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
I think you're looking for something along these lines.
Create an overlapping constraint in "parent". (The column "id" is unique, so {id, any-other-column} must also be unique.)
CREATE TABLE IF NOT EXISTS parent (
id INT NOT NULL AUTO_INCREMENT ,
status VARCHAR(45) NOT NULL ,
moreData VARCHAR(45) NULL ,
PRIMARY KEY (id),
UNIQUE (id, status)
)
ENGINE = InnoDB;
Add the status column in "child".
CREATE TABLE IF NOT EXISTS child (
parent_id INT NOT NULL ,
parent_status VARCHAR(45) NOT NULL ,
group_id INT NOT NULL ,
type INT NOT NULL ,
moreData VARCHAR(45) NULL ,
Primary key constraint doesn't have to change.
PRIMARY KEY (parent_id) ,
INDEX fk_child_group1_idx (group_id ASC) ,
Reference the pair of columns.
CONSTRAINT fk_child_parent
FOREIGN KEY (parent_id, parent_status )
REFERENCES parent (id, status )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT fk_child_group1
FOREIGN KEY (group_id )
REFERENCES group (id )
ON DELETE NO ACTION
ON UPDATE NO ACTION) ,
Whether you ought to cascade updates in fk_child_parent is application-dependent. Give that some thought.
And add a unique constraint on the set of columns you say should be unique.
CONSTRAINT uq_child
UNIQUE (group_id, type, parent_status)
REFERENCES group (id))
ENGINE = InnoDB;
One option is to create before insert trigger to do this verification, check constraints are not supported by mysql so that's not an option.
So I have looked it up for the past 2 days almost and I can't seem to figure out what is it that mysql doesn't let me add a foreign key. When I run the code for the second table that includes the foreign key I get the following error:
#1072 - Key column 'album' doesn't exist in table
I'm pretty sure there isn't any syntax error in my code as I have revised it few times now.
I have seen the same question before in stakOVF but the issues with those questions were very obvious syntax errors, however not of the solutions in those questions were relevant to my problem, none solved my issue.
So here is the code I am running and for which the error above is returned. Thanks in advance.
CREATE TABLE ‘Album’(
‘id’ INT AUTO_INCREMENT PRIMARY KEY ,
‘name’ VARCHAR( 35 ) NOT NULL
) ENGINE = InnoDB;
The above code runs with no problem, but when I run the code below the error comes up
CREATE TABLE ‘Picture’(
‘id_pk’ INT AUTO_INCREMENT PRIMARY KEY ,
‘album’ INT,
‘pictureURL’ VARCHAR( 270 ) NOT NULL ,
‘name’ VARCHAR( 35 ) NOT NULL ,
CONSTRAINT album_fk FOREIGN KEY ( album ) REFERENCES Album( id )
) ENGINE = InnoDB;
I have fiddled with the CONSTRAINT line and I had it also in the following form FOREIGN KEY (album) REFERENCES Album(id), that is without the constraint prepended.
THANK YOU ALL, after all there was a syntax error an like some said it is to do with the funny quotes, removing them, works like a charm. Many Thanks!
First you don't need any quote mark because any reserved word is used.
I tried to execute these sql queries without the quotes and it worked like a charm.
CREATE TABLE Album(
id INT AUTO_INCREMENT PRIMARY KEY ,
name VARCHAR( 35 ) NOT NULL
) ENGINE = InnoDB;
CREATE TABLE Picture(
id_pk INT AUTO_INCREMENT PRIMARY KEY ,
album INT,
pictureURL VARCHAR( 270 ) NOT NULL ,
name VARCHAR( 35 ) NOT NULL ,
CONSTRAINT album_fk FOREIGN KEY ( album ) REFERENCES Album( id )
) ENGINE = InnoDB;
The CREATE TABLE ‘Album’
creates a table with ‘Album’ name instead of Album, with ‘id’ and ‘name’ fields instead of id and name and so on
I think you should index the column 'album' before declaring it as a foreign key
Please check if this works
CREATE TABLE ‘Picture’(
‘id_pk’ INT AUTO_INCREMENT PRIMARY KEY ,
‘album’ INT,
‘pictureURL’ VARCHAR( 270 ) NOT NULL ,
‘name’ VARCHAR( 35 ) NOT NULL ,
INDEX (album),
CONSTRAINT album_fk FOREIGN KEY ( album ) REFERENCES Album( id )
) ENGINE = InnoDB;
As far as I know, foreign keys should be made indexes to actually make them foreign keys.
I have found this example in mysql dev documentation (http://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html)
CREATE TABLE parent (
id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (
id INT,
parent_id INT,
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id)
REFERENCES parent(id)
ON DELETE CASCADE
) ENGINE=INNODB;
I am not sure about it, but you might try to modify your code accordingly.
You seem to use interesting quotes, that become part of the name. Remove them and you should be fine
Can I suggest you get hold of MysQL Workbench. Its free and it's nice easy dislogs guide you through this sort of process.
This works for me, see what it does for you. I just changed the field name album to albumId to make the column usage more obvious.
CREATE TABLE `Picture` (
`id` INT NOT NULL AUTO_INCREMENT ,
`albumId` INT NULL ,
`pictureURL` VARCHAR(270) NOT NULL ,
`name` VARCHAR(35) NOT NULL ,
PRIMARY KEY (`id`) ,
INDEX `album_fk_idx` (`albumId` ASC) ,
CONSTRAINT `album_fk` FOREIGN KEY (`albumId` ) REFERENCES `album` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION)
ENGINE = InnoDB;
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
);
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.
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.