Multiple foreign key OR-relation - mysql

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.

Related

Adding a composite key in a foreign key constraint

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

Why is Primary Key's position relevant when creating a composite Foreign Key in MySql5.6?

I'm using MySQL 5.6 and I've read the MySql Reference guide regarding this but no where is it mentioned that the PK should be at the end of the list while creating a composite Foreign Key.
The only requirement in the guide that talks about columns is the following -
"In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order."
If so, then why doesn't the following work?
alter table table_1
add constraint "fk_key_1" FOREIGN KEY "ix_key_1" ("col_1", "col_2") REFERENCES "table_2" ("pk_col", "col_2") ON DELETE NO ACTION;
But this works -
alter table table_1
add constraint "fk_key_1" FOREIGN KEY "ix_key_1" ("col_1", "col_2") REFERENCES "table_2" ("col_2", "pk_col") ON DELETE NO ACTION;
The foreign key has to match the primary key (or some key, but preferably the primary one) -- both the types and order.
If this works:
FOREIGN KEY "ix_key_1" ("col_1", "col_2") REFERENCES "table_2 ("col_2", "id_col") ON DELETE NO ACTION;
It is because the primary key on table_2 is defined as (col_2, id_col) rather than (id_col, col_2).

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

MYSQL Add Foreign Key Constraint

I'm trying to add a constraint to my two tables, but I can't remember what the correct syntax is. Below are the two tables,
Is it.........
ALTER TABLE dispatch ADD CONSTRAINT fk_productlines FOREIGN KEY
(productlines_fkid) REFERENCES productlines(fkid)
Is that right?
When I try
ALTER TABLE dispatch ADD CONSTRAINT fk_productlines FOREIGN KEY
(fkid) REFERENCES productlines(fkid)
I get the following message:
#1072 - Key column 'fkid' doesn't exist in table
Is productlines.fkid a primary key ?
To make it a foreign key in dispatch it must be a primary key of productlines
To add a foreign key in dispatch :
ALTER TABLE dispatch
ADD CONSTRAINT fk_productlines
FOREIGN KEY (id) REFERENCES productlines(fkid)
ALTER TABLE product_lines ADD CONSTRAINT fk_productlines FOREIGN KEY
(fkid) REFERENCES dispatch(ID)
That should work.. Try it yourself!

Cannot add foreign key constraint on a date field

I have the following SQL statements:
CREATE TABLE patient(
Name varchar(255),
Geburtsdatum date,
CONSTRAINT pk_patient PRIMARY KEY (Name,Geburtsdatum)
);
CREATE TABLE fake(
Name varchar(255),
PName varchar(255),
PGeburtsdatum date,
CONSTRAINT pk_fake PRIMARY KEY (Name,PName,PGeburtsdatum),
CONSTRAINT fk_PName2 FOREIGN KEY (PName) REFERENCES patient(Name) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT fk_PGeburtsdatum FOREIGN KEY (PGeburtsdatum) REFERENCES patient(Geburtsdatum) ON DELETE CASCADE ON UPDATE CASCADE
);
This gives me the error "#1215 - Cannot add foreign key constraint". If I remove the last constraint in the second table creation everything works. All my other foreign key constraints work exactly the same way. What am I missing here?
Not sure why you tagged a mysql question as db2. Anyway, the MySQL documentation states:
MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan
So add an index in the Geburtsdatum column:
CREATE TABLE patient(
Name varchar(255),
Geburtsdatum date,
INDEX (Geburtsdatum),
CONSTRAINT pk_patient PRIMARY KEY (Name,Geburtsdatum)
);