Adding a composite key in a foreign key constraint - mysql

i am trying to add a new foreign key constraint and an index name
ALTER TABLE lng02_rpt_b_calvedets_msel_calfsire_secbreed ADD CONSTRAINT fklng021_lng02_rpt_b_calvedets_msel_calfsire_secbreed
FOREIGN KEY (hh_id,rpt_b_calvedets_rowid) REFERENCES lng02_rpt_b_calvedets(hh_id,rpt_b_calvedets_rowid);
The output error for my query is
Error Code: 1005. Can't create table `adggeth`.`#sql-e24_df1437` (errno: 150 "Foreign key constraint is incorrectly formed") 0.0057 sec
My query only works when i do not include two foreign keys as follows
ALTER TABLE lng02_rpt_b_calvedets_msel_calfsire_secbreed ADD CONSTRAINT fklng021_lng02_rpt_b_calvedets_msel_calfsire_secbreed
FOREIGN KEY (hh_id) REFERENCES lng02_rpt_b_calvedets(hh_id);
table definations as requested
CREATE TABLE `lng02_rpt_b_calvedets` (
`hh_id` varchar(10) DEFAULT NULL COMMENT 'Farmer',
`damid` varchar(80) NOT NULL COMMENT 'Tag ID of the mother',
`calvdatealv` date NOT NULL COMMENT 'Calving date',
-- i have removed most columns for you to get the picture
`rpt_b_calvedets_rowid` int(10) DEFAULT NULL,
-- i have removed most columns for you to get the picture
`calfstrawid` varchar(15) DEFAULT NULL,
PRIMARY KEY (`damid`,`calvdatealv`),
UNIQUE KEY `nosameanimalid` (`animalid`),
UNIQUE KEY `nosamecalftagid` (`tagid`),
KEY `fk5_lng02_rpt_b_calvedets_reg04_rpt_animreg` (`damid`),
KEY `fk6_lng02_rpt_b_calvedets_lng02_lkpsex` (`sex`),
KEY `fk7_lng02_rpt_b_calvedets_lng02_lkpcalvtype` (`calvtype`),
KEY `fk8_lng02_rpt_b_calvedets_lng02_lkpeasecalv` (`easecalv`),
KEY `fk9_lng02_rpt_b_calvedets_reg04_lkpsiretype` (`siretype`),
KEY `fk10_lng02_rpt_b_calvedets_reg04_rpt_animreg` (`siretag`),
KEY `fk11_lng02_rpt_b_calvedets_reg02_lkpe2_catlebreed` (`sirebreed`),
KEY `fk12_lng02_rpt_b_calvedets_reg03_lkpownbull_breedcomp` (`sirecomp`),
KEY `fk13_lng02_rpt_b_calvedets_reg02_lkpe2_catlebreed` (`strawbreed`),
KEY `fk14_lng02_rpt_b_calvedets_reg03_lkpownbull_breedcomp` (`strawcomp`),
KEY `fk15_lng02_rpt_b_calvedets_lng02_lkpfeedmth` (`feedmth`),
KEY `fk16_lng02_rpt_b_calvedets_lng02_lkpintuse` (`intuse`),
KEY `fk17_lng02_rpt_b_calvedets_lng02_lkpwhydead` (`whydead`),
KEY `longDIDX1` (`siretag`),
KEY `fk13_lng02_rpt_b_calvedets_lkpbirthtyp` (`birthtyp`),
KEY `fklng02_lng02_rpt_b_calvedets` (`hh_id`),
CONSTRAINT `fk10_lng02_rpt_b_calvedets_reg04_rpt_animreg` FOREIGN KEY (`siretag`) REFERENCES `reg04_rpt_animreg` (`animalid`) ON UPDATE NO ACTION,
CONSTRAINT `fk11_lng02_rpt_b_calvedets_reg02_lkpe2_catlebreed` FOREIGN KEY (`sirebreed`) REFERENCES `reg02_lkpe2_catlebreed` (`e2_catlebreed_cod`) ON UPDATE NO ACTION,
CONSTRAINT `fk12_lng02_rpt_b_calvedets_reg03_lkpownbull_breedcomp` FOREIGN KEY (`sirecomp`) REFERENCES `reg03_lkpownbull_breedcomp` (`ownbull_breedcomp_cod`) ON UPDATE NO ACTION,
CONSTRAINT `fk13_lng02_rpt_b_calvedets_lkpbirthtyp` FOREIGN KEY (`birthtyp`) REFERENCES `lng02_lkpbirthtyp` (`birthtyp_cod`),
CONSTRAINT `fk13_lng02_rpt_b_calvedets_reg02_lkpe2_catlebreed` FOREIGN KEY (`strawbreed`) REFERENCES `reg02_lkpe2_catlebreed` (`e2_catlebreed_cod`) ON UPDATE NO ACTION,
CONSTRAINT `fk14_lng02_rpt_b_calvedets_reg03_lkpownbull_breedcomp` FOREIGN KEY (`strawcomp`) REFERENCES `reg03_lkpownbull_breedcomp` (`ownbull_breedcomp_cod`) ON UPDATE NO ACTION,
CONSTRAINT `fk15_lng02_rpt_b_calvedets_lng02_lkpfeedmth` FOREIGN KEY (`feedmth`) REFERENCES `lng02_lkpfeedmth` (`feedmth_cod`) ON UPDATE NO ACTION,
CONSTRAINT `fk16_lng02_rpt_b_calvedets_lng02_lkpintuse` FOREIGN KEY (`intuse`) REFERENCES `lng02_lkpintuse` (`intuse_cod`) ON UPDATE NO ACTION,
CONSTRAINT `fk6_lng02_rpt_b_calvedets_lng02_lkpsex` FOREIGN KEY (`sex`) REFERENCES `lng02_lkpsex` (`sex_cod`) ON UPDATE NO ACTION,
CONSTRAINT `fk7_lng02_rpt_b_calvedets_lng02_lkpcalvtype` FOREIGN KEY (`calvtype`) REFERENCES `lng02_lkpcalvtype` (`calvtype_cod`) ON UPDATE NO ACTION,
CONSTRAINT `fk8_lng02_rpt_b_calvedets_lng02_lkpeasecalv` FOREIGN KEY (`easecalv`) REFERENCES `lng02_lkpeasecalv` (`easecalv_cod`) ON UPDATE NO ACTION,
CONSTRAINT `fk9_lng02_rpt_b_calvedets_reg04_lkpsiretype` FOREIGN KEY (`siretype`) REFERENCES `reg04_lkpsiretype` (`siretype_cod`) ON UPDATE NO ACTION,
CONSTRAINT `fklng02_lng02_rpt_b_calvedets` FOREIGN KEY (`hh_id`) REFERENCES `lng01_maininfo` (`hh_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Registry for each calving';

To create a composite foreign key, or even a single field one, the referenced table must have an index on the fields the foreign key references.
Example: If B references A with (f1, f2), then A must have an index on (f1, f2). An index on (f1, f2, fX) will also suffice; but (f2, f1) will not, nor will separate indexes on (f1) and (f2).

Related

MySQL error #1215: Cannot add Foreign Key Constraint

I'm trying to implement the tables shown in the picture:
this picture
(database scheme taken from http://www.databaseanswers.org/data_models/recipes/index.htm).
But I'm having problems with the Recipe_step_ingredients table. When adding foreign key constraints, I get error #1215 for the recipe_steps_id constraint (when not adding that constraint, I don't get the error and I can add the other two constraints).
Here is may command for creating the table:
CREATE TABLE recipe_step_ingredients (
recipe_id INTEGER,
step_number INTEGER,
ingredient_id INTEGER,
amount_required VARCHAR(128),
CONSTRAINT FOREIGN KEY (recipe_id) REFERENCES recipe_steps (recipe_id) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY (step_number) REFERENCES recipe_steps (step_number) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY (ingredient_id) REFERENCES ingredients (ingredient_id) ON DELETE CASCADE ON UPDATE CASCADE,
PRIMARY KEY (recipe_id, step_number, ingredient_id)
) ENGINE = INNODB
Anybody knows what could be the problem with it?
EDIT: Changed the code to match the naming conventions in the picture.
Also, here is the rest of the DDL I used:
CREATE TABLE recipes (
recipe_id INTEGER NOT NULL AUTO_INCREMENT,
recipe_name VARCHAR(128),
recipe_description VARCHAR(4096),
PRIMARY KEY (recipe_id),
INDEX (recipe_name)
) ENGINE = INNODB
CREATE TABLE recipe_steps (
recipe_id INTEGER,
step_number INTEGER,
instructions VARCHAR(4096),
CONSTRAINT FOREIGN KEY (recipe_id) REFERENCES recipes (recipe_id) ON DELETE CASCADE ON UPDATE CASCADE,
PRIMARY KEY (recipe_id, step_number)
) ENGINE = INNODB
CREATE TABLE ingredient_types (
ingredient_type_id INTEGER NOT NULL AUTO_INCREMENT,
ingredient_type_description VARCHAR(4096),
PRIMARY KEY (ingredient_type_id)
) ENGINE = INNODB
ALTER TABLE ingredient_types ADD COLUMN ingredient_type_name VARCHAR(128);
ALTER TABLE ingredient_types ADD INDEX(ingredient_type_name);
CREATE TABLE ingredients (
ingredient_id INTEGER NOT NULL AUTO_INCREMENT,
ingredient_type_id INTEGER,
ingredient_name VARCHAR(128),
CONSTRAINT FOREIGN KEY (ingredient_type_id) REFERENCES ingredient_types (ingredient_type_id) ON DELETE CASCADE ON UPDATE CASCADE,
PRIMARY KEY (ingredient_id),
INDEX (ingredient_name)
) ENGINE = INNODB
CREATE TABLE recipe_step_ingredients (
recipe_id INTEGER,
step_number INTEGER,
ingredient_id INTEGER,
amount_required VARCHAR(128),
CONSTRAINT FOREIGN KEY (recipe_id) REFERENCES recipe_steps (recipe_id) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY (step_number) REFERENCES recipe_steps (step_number) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY (ingredient_id) REFERENCES ingredients (ingredient_id) ON DELETE CASCADE ON UPDATE CASCADE,
PRIMARY KEY (recipe_id, step_number, ingredient_id)
) ENGINE = INNODB
Make sure that:
the foreign key references ALL the attributes of the key of the referenced relation (you cannot reference only some of them). SO if the key of R is (A,B), you should reference both A and B. You cannot reference only A or only B.
the attribute(s) you are referencing in a foreign key constraint is defined as UNIQUE or is the Primary key of the relation. In Mysql this can also be done by defining the attribute a KEY or UNIQUE KEY.
If you are referencing the primary key you don't need to indicate the name of the attribute after the table (the default is its primary key).
In your case,
make sure that the table recipe_steps has an attribute recipe_steps_id, and
this attribute is either UNIQUE KEY, KEY or the primary key of the relation
Also, make sure the corresponding index (for the key) has been created.

#1215 - Cannot add foreign key constraint

I need help in something for my work.
I have this code:
ALTER TABLE `utentes_old`
ADD CONSTRAINT `utentes_old_ibfk_1` FOREIGN KEY (`idConcelho`) REFERENCES `concelhos` (`id`),
ADD CONSTRAINT `utentes_old_ibfk_2` FOREIGN KEY (`idFreguesia`) REFERENCES `freguesias` (`id`),
ADD CONSTRAINT `utentes_old_ibfk_3` FOREIGN KEY (`idEstadoCivil`) REFERENCES `estadoscivis` (`id`),
ADD CONSTRAINT `utentes_old_ibfk_4` FOREIGN KEY (`idHabilitacoes`) REFERENCES `habilitacoes` (`id`),
ADD CONSTRAINT `utentes_old_ibfk_5` FOREIGN KEY (`idGrupoEtario`) REFERENCES `gruposetarios` (`id`),
ADD CONSTRAINT `utentes_old_ibfk_6` FOREIGN KEY (`idGenero`) REFERENCES `generos` (`id`),
ADD CONSTRAINT `utentes_old_ibfk_7` FOREIGN KEY (`idSituacaoRegularizada`) REFERENCES `situacaonopaisregularizada` (`id`),
ADD CONSTRAINT `utentes_old_ibfk_8` FOREIGN KEY (`idInscritoCE`) REFERENCES `inscritocentrodeemprego` (`id`),
ADD CONSTRAINT `utentes_old_ibfk_9` FOREIGN KEY (`idSituacaoDeEmprego`) REFERENCES `situacaodeemprego` (`id`),
ADD CONSTRAINT `utentes_old_ibfk_10` FOREIGN KEY (`idTempoDesemprego`) REFERENCES `tempodesemprego` (`id`),
ADD CONSTRAINT `utentes_old_ibfk_11` FOREIGN KEY (`idFrontOfficeSinalizador`) REFERENCES `instituicoes` (`id`),
ADD CONSTRAINT `utentes_old_ibfk_12` FOREIGN KEY (`idTecnico`) REFERENCES `tecnicos` (`id`);
But when I import the script to phpmyadmin they give me this error:
SQL query:
--
-- Limitadores para a tabela `utentes_old`
--
ALTER TABLE `utentes_old`
ADD CONSTRAINT `utentes_old_ibfk_1` FOREIGN KEY (`idConcelho`) REFERENCES `concelhos` (`id`),
ADD CONSTRAINT `utentes_old_ibfk_2` FOREIGN KEY (`idFreguesia`) REFERENCES `freguesias` (`id`),
ADD CONSTRAINT `utentes_old_ibfk_3` FOREIGN KEY (`idEstadoCivil`) REFERENCES `estadoscivis` (`id`),
ADD CONSTRAINT `utentes_old_ibfk_4` FOREIGN KEY (`idHabilitacoes`) REFERENCES `habilitacoes` (`id`),
ADD CONSTRAINT `utentes_old_ibfk_5` FOREIGN KEY (`idGrupoEtario`) REFERENCES `gruposetarios` (`id`),
ADD CONSTRAINT `utentes_old_ibfk_6` FOREIGN KEY (`idGenero`) REFERENCES `generos` (`id`),
ADD CONSTRAINT `utentes_old_ibfk_7` FOREIGN KEY (`idSituacaoRegularizada`) REFERENCES `situacaonopaisregularizada` (`id`),
ADD CONSTRAINT `utentes_old_ibfk_8` FOREIGN KEY (`idInscritoCE`) REFERENCES `inscritocentrodeemprego` (`id`),
ADD CONSTRAINT `utentes_old_ibfk_9` FOREIGN KEY (`idSituacaoDeEmprego`) REFERENCES `situac[...]
MySQL said: Documentation
#1215 - Cannot add foreign key constraint
Please can someone help me?
Removes the single quotes which you have given for table name , constraint name,reference name . It is a syntax error .
The two most common errors are that foreign key and primary key/index don not have the exact same data type, or the primary key is not defined correctly.
Also you don't need all those backticks / single quotes. You only need them when your names and identifiers contain whitespace, or special characters, which is not the case in your statements.
Without having all of your database schema it is really hard to tell which one is causing the problem, but I would check various things:
Ensure that a constraint with a given name doesn't already exist. You can't have duplicate constraints.
Ensure the data type of the column and the one it references are the same.
Since you're using foreign key, verify that the "id" column in each of the adjacent tables are primary keys. You cannot create a foreign key reference to a column that is not the primary key.
There may be others, and I will edit to add as I think of them, but these are three most common situations that I see myself.

SQL syntax error in adding a constraint in ALTER TABLE for mysql

I have another SQL error that says
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ADD CONSTRAINT fk_org1_id FOREIGN KEY (org_ID) REFERENCES organization (`o' at line 1
I don't know why I have this error when in fact, I followed correctly the proper syntax for adding a constraint in ALTER TABLE. Can someone help me?
Here is my sql code:
ALTER TABLE `administration`
ADD CONSTRAINT `fk_stud3_id` FOREIGN KEY (`stud_ID`) REFERENCES `student` (`stud_ID`),
ADD CONSTRAINT `fk_faculty3_ID` FOREIGN KEY (`faculty_ID`) REFERENCES `faculty` (`faculty_ID`);
ADD CONSTRAINT `fk_org1_id` FOREIGN KEY (`org_ID`) REFERENCES `organization` (`org_ID`)
ALTER TABLE `student_list`
ADD CONSTRAINT `fk_stud4_id` FOREIGN KEY (`stud_ID`) REFERENCES `student` (`stud_ID`),
ADD CONSTRAINT `fk_admin2_id` FOREIGN KEY (`admin_ID`) REFERENCES `administration` (`admin_ID`);
You have terminated your query on wrong place.
Your query is:
ALTER TABLE `administration`
ADD CONSTRAINT `fk_stud3_id` FOREIGN KEY (`stud_ID`) REFERENCES `student` (`stud_ID`),
ADD CONSTRAINT `fk_faculty3_ID` FOREIGN KEY (`faculty_ID`) REFERENCES `faculty` (`faculty_ID`);
ADD CONSTRAINT `fk_org1_id` FOREIGN KEY (`org_ID`) REFERENCES `organization` (`org_ID`)
should be-
ALTER TABLE `administration`
ADD CONSTRAINT `fk_stud3_id` FOREIGN KEY (`stud_ID`) REFERENCES `student` (`stud_ID`),
ADD CONSTRAINT `fk_faculty3_ID` FOREIGN KEY (`faculty_ID`) REFERENCES `faculty` (`faculty_ID`),
ADD CONSTRAINT `fk_org1_id` FOREIGN KEY (`org_ID`) REFERENCES `organization` (`org_ID`);
Small mistake, remove ; semicolon
ALTER TABLE `administration` ADD CONSTRAINT `fk_stud3_id` FOREIGN KEY (`stud_ID`) REFERENCES `student` (`stud_ID`),
ADD CONSTRAINT `fk_faculty3_ID` FOREIGN KEY (`faculty_ID`)
REFERENCES `faculty` (`faculty_ID`);// here change semicolon to comma.
ADD CONSTRAINT `fk_org1_id` FOREIGN KEY (`org_ID`)
REFERENCES `organization` (`org_ID`); // add semicolon here.

MySql 5.6.17 Error #1215 - Cannot add foreign key constraint

I'm tryin to create a table "SIGNATURE" in my database I want this table to have a double primary key and add a foreign key constraint to both primary key that references table "TRAITEMENT"
CREATE TABLE TRAITEMENT (
id INTEGER NOT NULL,
dateHeurePrevue DATETIME NOT NULL,
commentaire LONGTEXT,
dateValidation TIMESTAMP,
CONSTRAINT PK PRIMARY KEY (id,dateHeurePrevue),
CONSTRAINT FK_traitement_consigne FOREIGN KEY (id) REFERENCES consigne(id)) ENGINE=InnoDB;
create unique index id_dateheureprevue on traitement(id, dateheureprevue);
CREATE TABLE SIGNATURE (
id INTEGER NOT NULL,
idPersonne INTEGER NOT NULL,
dateTimeTraitement DATETIME NOT NULL,
retard INTEGER,
motifRetard INTEGER,
heureEffectiveTraitement DATETIME NOT NULL,
CONSTRAINT PK PRIMARY KEY (id,dateTimeTraitement),
CONSTRAINT FK_id FOREIGN KEY (id) REFERENCES traitement(id),
CONSTRAINT FK_idPersonne FOREIGN KEY (idPersonne) REFERENCES personne(id),
CONSTRAINT FK_motifRetard FOREIGN KEY (motifRetard) REFERENCES retard(id),
CONSTRAINT FK_dateTimeTraitement FOREIGN KEY (dateTimeTraitement) REFERENCES traitement(dateHeurePrevue))ENGINE=InnoDB;
create unique index id_dateTimetraitement on signature(id, dateTimeTraitement);
Obviously ( I tried to remove it and it worked fine) the problem comes from this forign key :
CONSTRAINT FK_dateTimeTraitement FOREIGN KEY (dateTimeTraitement) REFERENCES traitement(dateHeurePrevue)
I don't understand, i don't see any conflicts of type,keys...
If anyone can help me solve this problem...
Thanks in advance
Your foreign key must be exactly equal to the primary key fields, so:
CONSTRAINT FK_dateTimeTraitement FOREIGN KEY (id, dateTimeTraitement) REFERENCES traitement(id, dateHeurePrevue)

Multiple foreign key OR-relation

I have the following two foreign keys:
CONSTRAINT `FK_rel_object-user_users` FOREIGN KEY (`User`) REFERENCES `_users` (`ID`),
CONSTRAINT `FK__rel_object-user__map_usernames` FOREIGN KEY (`User`) REFERENCES `_map_usernames` (`ID`)
How can I define, that the data should exist in _users OR _map_usernames instead of AND
No.
That is, you cannot create a foreign key constraint this way. You can however, use a foreign key without a foreign key constraint.
All a foreign key is, is the value of another table's (or another record in the same table) primary key, which can be used in joins. In fact, you could reference fields other than the primary key, if all you need is to use the value for joins.