I'm having a bit of a strange problem, I'm trying to add a foreign key to one table that references another, but it is failing for some reason. With my limited knowledge of MySQL, the only thing that could possibly be suspect is that there is a foreign key on a different table referencing the one I am trying to reference.
Here is a picture of my table relationships, generated via workbench: Relationships
CREATE TABLE `beds` (
`bedId` int(11) NOT NULL,
`wardId` int(11) DEFAULT NULL,
`depId` int(11) DEFAULT NULL,
`desc` varchar(45) DEFAULT NULL,
PRIMARY KEY (`bedId`),
KEY `departmentId_idx` (`depId`),
KEY `wardId_idx` (`wardId`),
CONSTRAINT `departmentId` FOREIGN KEY (`depId`)
REFERENCES `department` (`Department_Id`)
ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `wardId` FOREIGN KEY (`wardId`) REFERENCES `wards` (`wardId`)
ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails
(`asiahospitaldb`.`beds`, CONSTRAINT `departmentId` FOREIGN KEY (`depId`)
REFERENCES `department` (`Department_Id`)
ON DELETE NO ACTION ON UPDATE NO ACTION)
SQL Statement:
INSERT INTO `asiahospitaldb`.`Beds` (`bedId`, `wardId`, `depId`, `desc`)
VALUES ('456', '7444', '4555', 'ikiuj')
This
ERROR 1452: Cannot add or update a child row: a foreign key constraint
fails (`asiahospitaldb`.`beds`, CONSTRAINT `departmentId` FOREIGN KEY
(`depId`) REFERENCES `department` (`Department_Id`) ON DELETE NO
`enter code here`ACTION ON UPDATE NO ACTION)
is telling you that the row you have inserted expects a corresponding value for department/department_id for the value you have inserted into column depId (as Omesh pointed out). The important bit is here:
(depId) REFERENCES department (Department_Id)
In other words, you have tried to create a bed in a non-existent department.
Related
I've created two tables to do mappings between users. First for users and second for user-mappings. Deletion of users work well, but if I try to update the user id the foreign key constraints from the mapping table fail (without a helpful error output).
CREATE TABLE user (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(55),
PRIMARY KEY (`id`)
);
CREATE TABLE user_map (
map_id INT NOT NULL AUTO_INCREMENT,
user_a INT,
user_b INT,
PRIMARY KEY (`map_id`),
UNIQUE KEY `one_way` (`user_a`,`user_b`),
UNIQUE KEY `other_way` (`user_b`,`user_a`),
CONSTRAINT `acc_connections_ibfk_1` FOREIGN KEY (`user_a`) REFERENCES `user` (`id`) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT `acc_connections_ibfk_2` FOREIGN KEY (`user_b`) REFERENCES `user` (`id`) ON UPDATE CASCADE ON DELETE CASCADE
)
Example Data:
INSERT INTO user (name) VALUES ("User A");
INSERT INTO user_map (user_a,user_b) VALUES (1,1);
If I try to update the user id afterwards I get the following error:
Cannot add or update a child row: a foreign key constraint fails
(`test_db`.`user_map`, CONSTRAINT `user_map_ibfk_2`
FOREIGN KEY (`user_b`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)
DB Fiddle (Demo)
Interestingly deleting the parent row (user table) succeeds without an error.
What am I doing wrong? I see no reason why this should fail.
I don't know if this is a bug or intended behavior.
As a workaround, if your version of MySql is 8.0.13+, which supports Functional Key Parts, you can use 1 UNIQUE KEY (to check the uniqueness of the combination of the 2 columns) instead of the 2 keys and the UPDATE statement will work:
CREATE TABLE IF NOT EXISTS user_map (
map_id INT NOT NULL AUTO_INCREMENT,
user_a INT,
user_b INT,
PRIMARY KEY (`map_id`),
UNIQUE KEY unk_users((LEAST(`user_a`,`user_b`)), (GREATEST(`user_a`,`user_b`))),
CONSTRAINT `acc_connections_ibfk_1` FOREIGN KEY (`user_a`) REFERENCES `user` (`id`) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT `acc_connections_ibfk_2` FOREIGN KEY (`user_b`) REFERENCES `user` (`id`) ON UPDATE CASCADE ON DELETE CASCADE
);
See the demo.
I'm trying to create two relations by MySQL, while I was creating the second relation "t2", I added a foreign constraint to the first relation "t1".
The first table "t1" was been built successfully, but it showed "Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'FK2' in the referenced table 't1'" during creating the second table "t2".
I have checked some issues like mine, some solutions were the referenced attribute in the first table should be unique or primary key. But "Mon" already has been the PK in the first table.
What's wrong in my code?
create table t1
( Num INT(10) NOT NULL,
Mon VARCHAR(7) NOT NULL,
CONSTRAINT PK1 PRIMARY KEY (Num, Mon)
);
CREATE TABLE t2
( Num INT(10) NOT NULL,
Mon VARCHAR(7) NOT NULL,
Totle_Income Decimal(9,2) DEFAULT 0,
CONSTRAINT PK2 PRIMARY KEY (Num, Mon),
CONSTRAINT FK1 FOREIGN KEY (Num) REFERENCES t1(Num)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FK2 FOREIGN KEY (Mon) REFERENCES t1(Mon)
ON DELETE CASCADE ON UPDATE CASCADE
);
t1.mon is only the second component of the primary key, thus also only the second component of the index. That doesn't usefully index t1.mon, it needed to be the first or only component of the index.
But you likely want to reference the complete key. So the foreign key constraint should include both columns rather than having two constraints for each part of the key.
...
CONSTRAINT FK1
FOREIGN KEY (Num,
Mon)
REFERENCES t1
(Num,
Mon)
ON DELETE CASCADE
ON UPDATE CASCADE,
...
t1.monis not unique and therefore can not be refered as a foreign_key
I found some threads about the error. But all the solutions does not work for me.
My system already had the following tables:
CREATE TABLE `bdo2_agencia` (
`cod_uf` char(2) NOT NULL,
`cod_agencia` char(9) NOT NULL,
`nome` varchar(100) NOT NULL,
PRIMARY KEY (`cod_uf`,`cod_agencia`),
KEY `fk_agencia_2_uf_idx` (`cod_uf`),
CONSTRAINT `fk_agencia_2_uf` FOREIGN KEY (`cod_uf`) REFERENCES `bdo2_uf` (`cod_uf`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `bdo2_login` (
`login` char(30) NOT NULL,
`ativo` tinyint(1) DEFAULT '1' COMMENT 'informa se o login está ativo',
PRIMARY KEY (`login`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I tried to create another table between them, defining a relationship N:M
CREATE TABLE IF NOT EXISTS `bdo2`.`bdo2_login_agencia` (
`cod_uf` CHAR(2) NOT NULL,
`cod_agencia` CHAR(9) NOT NULL,
`login` CHAR(30) NOT NULL,
PRIMARY KEY (`cod_uf`, `cod_agencia`, `login`),
INDEX `fk_login_2_login_agencia_idx` (`login` ASC),
INDEX `fk_agencia_2_login_agencia_idx` (`cod_uf` ASC, `cod_agencia` ASC),
CONSTRAINT `fk_agencia_2_login_agencia`
FOREIGN KEY (`cod_uf` , `cod_agencia`)
REFERENCES `bdo2`.`bdo2_agencia` (`cod_uf` , `cod_agencia`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_login_2_login_agencia`
FOREIGN KEY (`login`) REFERENCES `bdo2`.`bdo2_login` (`login`) ON DELETE NO ACTION ON UPDATE NO ACTION)
ENGINE = InnoDB;
but I received the following error:
Error Code: 1215. Cannot add foreign key constraint
With the command
SHOW ENGINE innodb STATUS
I got the following message:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
2016-03-22 10:14:05 7fe09c49f700 Error in foreign key constraint of table bdo2/bdo2_login_agencia:
FOREIGN KEY (`cod_uf` , `cod_agencia`)
REFERENCES `bdo2`.`bdo2_agencia` (`cod_uf` , `cod_agencia`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_login_2_login_agencia`
FOREIGN KEY (`login`) REFERENCES `bdo2`.`bdo2_login` (`login`)
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.6/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
So I created the table without the constraints and I tried to create the constraints individually
ALTER TABLE `bdo2`.`bdo2_login_agencia`
ADD INDEX `fk_agencia_2_login_agencia_idx` (`cod_uf` ASC, `cod_agencia` ASC),
ADD INDEX `fk_login_2_login_agencia_idx` (`login` ASC);
ALTER TABLE `bdo2`.`bdo2_login_agencia`
ADD CONSTRAINT `fk_agencia_2_login_agencia`
FOREIGN KEY (`cod_uf` , `cod_agencia`)
REFERENCES `bdo2`.`bdo2_agencia` (`cod_uf` , `cod_agencia`)
ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_login_2_login_agencia`
FOREIGN KEY (`login`)
REFERENCES `bdo2`.`bdo2_login` (`login`)
ON DELETE NO ACTION ON UPDATE NO ACTION;
but received the following error:
ERROR 1822: Failed to add the foreign key constaint. Missing index for constraint 'fk_agencia_2_login_agencia' in the referenced table 'bdo2_agencia'
If index exists, why returns this message?
It would be a bug of version? I tested in two servers (versions 5.6.23 and 5.6.29) on Linux, both presented the same problem.
The problem was in COLLATION. I found that bdo2_login and bdo2_agencia tables were with CHARSET = utf8, but did not realize that the Workbench put the new table as latin1. It was enough to hit the CHARSET and COLLATION that solved.
I had the same problem in another creation of FK and the problem was COLLATION only the columns. The table had the PK had COLLATION utf8 and the column was created as FK as latin1. It was enough to hit the COLLATION that the problem was solved.
In mysql, when i try to do:
INSERT INTO Comandes_Productes(Id_Comanda, Id_Producte) VALUES ('60', '10009') --> (or others values)
for example, i get this error message: #1452 - Cannot add or update a child row: a foreign key constraint fails (cafeteria.comandes_productes, CONSTRAINT comandes_productes_ibfk_2 FOREIGN KEY (Id_Producte) REFERENCES comandes (Id_Comanda) ON UPDATE CASCADE)
I try to do a lot of solutions that are proposed the next link, but, too i didn't solve the error.
Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails
I will get you the code, to see if i have an error in it.
CREATE TABLES:
CREATE TABLE Comandes (
Id_Comanda INTEGER(9) AUTO_INCREMENT,
Quantitat INTEGER(4),
Id_Proveidor INTEGER(9) NOT NULL,
Data DATE,
PRIMARY KEY (Id_Comanda),
FOREIGN KEY (Id_Proveidor) REFERENCES Proveidors(Id_Proveidor) ON UPDATE CASCADE
) CHARACTER SET utf8 COLLATE utf8_spanish_ci;
CREATE TABLE Productes (
Id_Producte INTEGER(9) AUTO_INCREMENT,
Marca VARCHAR(15),
Nom_Producte VARCHAR(30),
Preu_Producte FLOAT(4,2),
Quantitat INTEGER(4),
Descripcio VARCHAR(50),
Id_Proveidor INTEGER(9),
PRIMARY KEY (Id_Producte)
) AUTO_INCREMENT=10001 CHARACTER SET utf8 COLLATE utf8_spanish_ci;
CREATE TABLE Comandes_Productes (
Id_Comanda INTEGER(9),
Id_Producte INTEGER(9),
PRIMARY KEY (Id_Producte, Id_Comanda),
FOREIGN KEY (Id_Producte) REFERENCES Productes (Id_Producte) ON UPDATE CASCADE,
FOREIGN KEY (Id_Producte) REFERENCES Comandes (Id_Comanda) ON UPDATE CASCADE
) CHARACTER SET utf8 COLLATE utf8_spanish_ci;
And yes, i already have the foreing keys values in the tables "Comandes" and "Productes". All tables are with InnoDB, too i try to delete all database and create other time, but.. nothing... I see the specifications of the tables and too are all the same.
In what i fails? Please help me! I can't continue with my project...
I see one problem with your Comandes_Productes table:
FOREIGN KEY (Id_Producte) REFERENCES Comandes (Id_Comanda) ON UPDATE CASCADE
probably it should be
FOREIGN KEY (Id_Comanda) REFERENCES Comandes (Id_Comanda) ON UPDATE CASCADE
Also, I am not much into MySQL, but probably you shoud not use single quotes when entering numerical values.
I am working on a PHP application that uses a database extensively. My coworker who set up the database, set up the tables to use foreign keys. Here is the statement I am using:
INSERT INTO patients (ethnicity, gender)
VALUES (1, 1);
INSERT INTO sessions (patient_id, submitted, age_in_years, video, annotated)
VALUES (LAST_INSERT_ID(), NOW(), 0, '', FALSE);
The first statement works. However, I get the following error with the second statement.
#1452 - Cannot add or update a child row: a foreign key constraint fails (`<database name>/sessions`, CONSTRAINT `fk_sessions_1` FOREIGN KEY (`patient_id`) REFERENCES `patient` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)
I have confirmed that LAST_INSERT_ID() returns the expected value.
How can I fix this?
Below is how we set up the sessions table
CREATE TABLE IF NOT EXISTS `sessions` (
`id` int(11) NOT NULL auto_increment,
`patient_id` int(11) NOT NULL,
`severity` enum('Minimal Symptoms of Autism Spectrum Disorder','Mild-to-Moderate Symptoms of Autism Spectrum Disorder','Severe Symtoms of Autism Spectrum Disorder') default NULL,
`submitted` datetime default NULL,
`age_in_years` int(11) NOT NULL,
`video` text NOT NULL,
`annotated` tinyint(1) default '0',
PRIMARY KEY (`id`),
KEY `fk_sessions_1` (`patient_id`),
KEY `age_in_years` (`age_in_years`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
ALTER TABLE `sessions`
ADD CONSTRAINT `fk_sessions_1` FOREIGN KEY (`patient_id`) REFERENCES `patient` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
EDIT: Removed unnecessary details. If you feel you need more, feel free to look at the first version of this post.
It turns out that when my coworker added the foreign key, he had a typo in the table name that the foreign key references.
ALTER TABLE `sessions`
ADD CONSTRAINT `fk_sessions_1` FOREIGN KEY (`patient_id`) REFERENCES `patient` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
should be
ALTER TABLE `sessions`
ADD CONSTRAINT `fk_sessions_1` FOREIGN KEY (`patient_id`) REFERENCES `patients` (`id`) ON DELETE CASCADE;
The error is telling you exactly what's wrong.
You're attempting to insert a value in sessons.patient_id that does not exist in patients.id. This is how foreign key constraints work by design. Regardless of whether or not the value of LAST_UPDATE_ID() is what you expect, you need to confirm that the value is valid in patients.id.
Example:
patients
---------------
id | name
---------------
1 | john
2 | jane
If you try to insert "3" into sessions.patient_id, you will get the error you see because that id doesn't exist in patients.