Why mySql doesn't let me declare foreign key? - mysql

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;

Related

Duplicate key error in MySQL

The below query is resulting in an error. I created this query in MySQL Workbench
Error
SQL query:
-- -----------------------------------------------------
-- Table `smsdb`.`IntSupervisor`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `smsdb`.`IntSupervisor` (
`int_supr_id` VARCHAR( 32 ) NOT NULL ,
`cent_id` INT NOT NULL ,
INDEX `fk_IntSupervisor_Person1_idx` ( `int_supr_id` ASC ) ,
INDEX `fk_IntSupervisor_Center1_idx` ( `cent_id` ASC ) ,
PRIMARY KEY ( `int_supr_id` ) ,
CONSTRAINT `fk_parent_id` FOREIGN KEY ( `int_supr_id` )
REFERENCES `smsdb`.`Staff` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT ,
CONSTRAINT `fk_center_id` FOREIGN KEY ( `cent_id` )
REFERENCES `smsdb`.`Center` (`cent_id`
) ON DELETE CASCADE ON UPDATE RESTRICT
) ENGINE = InnoDB;
I got an error message on execution:
MySQL said: Documentation
#1022 - Can't write; duplicate key in table 'intsupervisor'
If anyone has any ideas on how I can resolve this issue, please guide me in the right direction. Thanks!
You can't have two foreign keys named the same thing across the whole query.
PRIMARY KEY ( `int_supr_id` ) ,
CONSTRAINT `fk_parent_id` FOREIGN KEY ( `int_supr_id` )
In the above statement, you can't redefine the index type on a single column.
So, how do I fix this annoying error?
Based on the structure of the database, you need to remove one of the two lines above. I'm guessing your linking to another table from the one you are creating, so I recommend replacing ...
PRIMARY KEY ( `int_supr_id` ) ,
CONSTRAINT `fk_parent_id` FOREIGN KEY ( `int_supr_id` )
With the following:
CONSTRAINT `fk_parent_id` FOREIGN KEY ( `int_supr_id` )
(if the above doesn't work, you likely need to specify a table name for the foreign key)
You are adding an index to the column 'int_supr_id' and then also add a primary_index to it. You can only add 1 index to it (well, in normal cases)
It probably throws an error because you making both primary and foreign keys on one column int_supr_id

Error 1215: Cannot add foreign key constraint

I built a database with mySql Workbench, but when I try to forward engineer my model to the server, I get the following error :
ERROR: Error 1215: Cannot add foreign key constraint
followed by the definition of the table where the foreign key is defined, salaire_annee_ca
I read similar topics to identify the usual causes for this error, and checked :
if the foreign key defined in salaire_annee_ca references the primary key of another table, which it does
if something in the code allowed my key to be null, which it doesn't
if the types of the reference and of the foreign key were the same
It seems to me that all these conditions are ok, so I don't understand why I still get that message. Here are the definitions of my tables :
These are the two main ones :
-- Table `credit_impot_db`.`salaires_annee`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `credit_impot_db`.`salaires_annee` (
`salaire_annee_id` INT(11) NOT NULL ,
`salaire_annuel` DOUBLE NOT NULL DEFAULT 0 ,
`heures_travaillees` DOUBLE NOT NULL DEFAULT 0 ,
`pourcentage_rsde` DOUBLE NOT NULL DEFAULT 0 ,
`jours_travailles` INT(3) NOT NULL DEFAULT 0 ,
PRIMARY KEY (`salaire_annee_id`) ,
CONSTRAINT `salaire_annee_id`
FOREIGN KEY (`salaire_annee_id` )
REFERENCES `credit_impot_db`.`employes_ac` (`employe_ac_id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
This one is at the origin of the message :
-- -----------------------------------------------------
-- Table `credit_impot_db`.`salaire_annee_ca`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `credit_impot_db`.`salaire_annee_ca` (
`salaire_annee_ca_id` INT(11) NOT NULL ,
PRIMARY KEY (`salaire_annee_ca_id`) ,
CONSTRAINT `salaire_annee_ca_id`
FOREIGN KEY (`salaire_annee_ca_id` )
REFERENCES `credit_impot_db`.`salaires_annee` (`salaire_annee_id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
And the following two are also referenced :
-- -----------------------------------------------------
-- Table `credit_impot_db`.`employes`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `credit_impot_db`.`employes` (
`employe_id` INT(11) NOT NULL AUTO_INCREMENT ,
`employe_nom` VARCHAR(255) NOT NULL ,
`employe_prenom` VARCHAR(255) NOT NULL ,
`employe_fonction` VARCHAR(255) NULL ,
`employe_experience` VARCHAR(255) NULL DEFAULT NULL ,
PRIMARY KEY (`employe_id`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `credit_impot_db`.`employes_ac`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `credit_impot_db`.`employes_ac` (
`employe_ac_id` INT(11) NOT NULL AUTO_INCREMENT ,
`fk_employe_ac_employe_id` INT(11) NULL ,
`fk_employe_ac_ac_id` INT(11) NULL ,
PRIMARY KEY (`employe_ac_id`) ,
INDEX `fk_employe_ac_employe_id_idx` (`fk_employe_ac_employe_id` ASC) ,
INDEX `fk_employe_ac_ac_id_idx` (`fk_employe_ac_ac_id` ASC) ,
CONSTRAINT `fk_employe_ac_employe_id`
FOREIGN KEY (`fk_employe_ac_employe_id` )
REFERENCES `credit_impot_db`.`employes` (`employe_id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_employe_ac_ac_id`
FOREIGN KEY (`fk_employe_ac_ac_id` )
REFERENCES `credit_impot_db`.`dossier_client` (`ac_id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
Any help would be appreciated!
I hit the dreaded error 1215 while using the Workbench and spent a long time trying to work out what was wrong. I eventually noticed that some of my tables were defined with "latin1 - default collation", while others were defined with "Schema Default". I had to expand the table definitions one by one in the EER diagram to see the option to change this. I changed all the definitions to "Schema Default" and the problem disappeared. Wow!
Ok I think I figured it out. It seems to be a problem with mySql Workbench, the error disappears if :
I first create my primary key in salaire_annee_ca,
Then Forward engineer my database
Declare my primary key as being a foreign key which references the primary key of salaire_annee
Forward engineer my database again
The error gets resolved:
To create a Foreign key for a table like this
CREATE TABLE users_so
(
username VARCHAR(10) NOT NULL,
password VARCHAR(32) NOT NULL,
enabled SMALLINT,
PRIMARY KEY (username)
);
The below code works fine
CREATE TABLE authorities_so
(
username VARCHAR(10) NOT NULL,
authority VARCHAR(10) NOT NULL,
FOREIGN KEY (username) REFERENCES users_so(username)
);
One of possible cause could be default storage engine on production db.
My problem was similar. I also worked with Workbench, and in local worked perfectly, also worked good in production, until I recreate schema on production server with Forward Engineering.
One of tables become MyISAM instead of InnoDb, and Row format from Don't use become Dynamic.
My solution was:
In Workbench,
Check every table that requires foreign keys to be InnoDb, and
Row format to be Default.

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

MySQL: Unable to create table (errno: 150)

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?

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.