Cannot insert row into table with foreign key field - mysql

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.

Related

MySQL Workbench :: Can't add a second foreign key to existing table

Apologies in advance for what is prob a duplicate post - I can't find my exact issue elsewhere. I'm taking a SQL course and using MySQL Workbench 6.3 as my sandbox. In my class project, I'm creating "Courses", "Professors" and "Teaches" tables. Here's the first two, abridged:
// CREATE DATABASE `project1'...
CREATE TABLE `courses` ( `cid` int(11) NOT NULL, ...more... PRIMARY KEY (`cid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `professors` ( `ssn` int(11) NOT NULL, ...more... PRIMARY KEY (`ssn`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
The "Teaches" tables is simple enough:
CREATE TABLE `teaches` (
`cid` int(11) NOT NULL,
`ssn` int(11) NOT NULL,
PRIMARY KEY (`cid`,`ssn`),
KEY `ssn_idx` (`ssn`),
CONSTRAINT `ssn` FOREIGN KEY (`ssn`) REFERENCES `professors` (`ssn`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
All of the SQL above is successful. But my problem is that "Teaches" needs a second foreign key back to "Courses." I would have thought this would do it:
ALTER TABLE `project1`.`teaches`
ADD CONSTRAINT `cid`
FOREIGN KEY (`cid`)
REFERENCES `project1`.`courses` (`cid`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
But MySQL hates it:
Operation failed: There was an error while applying the SQL script to the database.
ERROR 1022: Can't write; duplicate key in table '#sql-1060_1b'
SQL Statement:
ALTER TABLE `project1`.`teaches`
ADD CONSTRAINT `cid`
FOREIGN KEY (`cid`)
REFERENCES `project1`.`courses` (`cid`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
I'm baffled because I have other tables with two foreign key relations, and I'm not hitting this issue with them. (Yes, I've cloned their SQL create statements, but no luck.) The problem is described as "duplicate key in table '#sql-1060_1b'" but I can't figure out what table #sql-1060-1b might be. Any guidance?
Thanks to Norbert van Nobelen, who solved the problem - renaming the "Course" attribute from "cid" to "mycid" did the trick.

Mysql: Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails

I have this table:
CREATE TABLE comments(
comment_id int(11) NOT NULL auto_increment,
user_id int(11) NOT NULL,
product_id int(11) NOT NULL,
comment_text varchar(1000) COLLATE utf8_czech_ci NOT NULL,
uploaded datetime NOT NULL,
primary key(comment_id),
constraint fk_user_comments foreign key(user_id) references user(user_id) ON UPDATE CASCADE ON DELETE CASCADE,
constraint fk_product_comments foreign key(product_id) references product(product_id) ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci;
and I'm trying to insert data into this table.
INSERT INTO comments(user_id,product_id,comment_text,uploaded) VALUES(1,'brbr',1,Now());
But for some reason I keep getting this error:
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`project`.`comments`, CONSTRAINT `fk_product_comments` FOREIGN KEY (`product_id`) REFERENCES `product` (`product_id`) ON DELETE CASCADE ON UPDATE CASCADE)
User with id 1 exists and product with id 1 exists so now i have no idea whats causing the problem.
You've got your column list's order messed up.
You're attempting to insert a row with a product_id of 'brbr' (which MySQL treats as 0) and a comment text of 1 (which MySQL converts as to '1').
Reordering the the column list to match the values (or vise-versa) should solve it:
INSERT INTO comments
(user_id, product_id, comment_text, uploaded)
VALUES (1, 1, 'brbr', NOW());
-- Here ---^
This because you are not adding value according to your column sequence.
This is correct query.
INSERT INTO comments(user_id,product_id,comment_text,uploaded) VALUES(1,1,'brbr',Now())
I met the same problem today as I was dealing with Schema that wasn't designed by me. I added tables and relationships (FK) and things went KaBoom!
Upon investigation, I found the other buddy was using MyIsam Engine for that table and I was using InnoDB.
Changing the table from MyIsam to InnoDB ssolved the Issue!

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

I have created two tables in MySQL 5.6.11 as shown below by means of MySQL Workbench 5.2.47.
The country table:
delimiter $$
CREATE TABLE `country` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`country_name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INC
REMENT=2 DEFAULT CHARSET=utf8$$
The state_table:
delimiter $$
CREATE TABLE `state_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`state_name` varchar(45) DEFAULT NULL,
`country_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `country_fk` FOREIGN KEY (`id`) REFERENCES `country` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT=''$$
There is one row in the country table with the id 1. It allows only one (child) row to be inserted into its child table state_table. If more rows are attempted, then the following error occurs.
ERROR 1452: Cannot add or update a child row: a foreign key constraint
fails (social_networking.state_table, CONSTRAINT country_fk
FOREIGN KEY (id) REFERENCES country (id) ON DELETE CASCADE ON
UPDATE CASCADE)
SQL Statement:
INSERT INTO `social_networking`.`state_table` (`id`, `state_name`, `country_id`) VALUES ('2', 'xxx', '1')
Actually, I'm trying to map these tables using an ORM (JPA) where I always see only OneToOne relationship.
What am I missing?
Well, I find the answer, the solution, my english is not very well but I think can explain you. I get this error after try to create a trigger, My database was created in phpmyadmin, and this error was make me crazy, the problem was that I before create the trigger, I load a lot of data in my tables, and in my child table was some data that have no match in my parent table, ej: my child table "chat" have a "id_jugador=1" and in my parent table there wasn't that "id_jugador", that was my mistake, I hope help you, Argentina Rulz ;)
I think you have a typo in your foreign key constraint, country_id should probaby be the foreign key to country. When id is the foreign key, you can only insert one row since it just happens to get id=1 which is the same id as the row in country;
CONSTRAINT `country_fk` FOREIGN KEY (`id`)
REFERENCES `country` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
should probably be
CONSTRAINT `country_fk` FOREIGN KEY (`country_id`)
REFERENCES `country` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
An SQLfiddle to test with.
I had the same problem and it was not wrong relationships name.
I had problem with different records, ie, tried registering a record that did not exist in another table so generated this error.
Check if the record exists in another table to insert their correct relationship, otherwise, this error appears.
Hope this help you.
example:
table1(
id1 INT PRIMARY KEY,
name1 VARCHAR(50)
)
table2(
id2,<--- want to add FOREIGN KEY to this field
name2 VARCHAR(50)
)
Before adding constraint foreign key you must have the right value between id1 and id2, so you should update that id field with the value that map each other.
Possible Solution
if you have live data, then check all column values.
i.e. if you have 'x'->table as primary one having 'a'->column and 'y'->table as secondary with 'b'->column, then all values in 'b'->column must exist in 'a'->column if any value that exists in 'b'->column and not exist in 'a'->column then it will give as such error..
Hope this help.. for newbie..

ERROR 1452: Cannot add or update a child row

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.

MySQL Composite Foreign Key Insert Failing

I have 2 tables with a composite foreign key between the 2. When I try to insert a row into the child table, I get a restraint failure, even though the values exist in the parent table.
Here's a overview of the parent table:
CREATE TABLE `residual_reports` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`processor` enum('1','2','3') NOT NULL,
`posting_date` date NOT NULL DEFAULT '0000-00-00',
`approved_on` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `posting_date_2` (`processor`,`posting_date`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=latin1
The child table has the foreign key to the processor and posting date columns:
CREATE TABLE `residual_data` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`mid` varchar(29) DEFAULT NULL,
`processor` enum('1','2','3') NOT NULL,
`posting_date` date NOT NULL,
......
PRIMARY KEY (`id`),
KEY `residual_data_ibfk_1` (`processor`,`posting_date`),
CONSTRAINT `residual_data_ibfk_1` FOREIGN KEY (`processor`, `posting_date`) REFERENCES `residual_reports` (`processor`, `posting_date`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1
I inserted a row into the residual_reports table with processor = 1, and posting_date = 2010-03-10.
When I try to insert into the residual_data table with processor = 1, and posting_date = 2010-03-10.
INSERT INTO `residual_data`(processor,posting_date) VALUES ('1','2010-03-10');
I get an:
[Err] 1452 - Cannot add or update a child row: a foreign key constraint fails (residual_data, CONSTRAINT residual_data_ibfk_1 FOREIGN KEY (processor, posting_date) REFERENCES residual_reports (processor, posting_date) ON UPDATE CASCADE)
Verified that the values definitely exist in the parent table, but still get foreign key restraint errors. Is there something I'm missing with a composite foreign key?
I would suspect the ENUM's, did you do something with them afterwards? Did you change values or so?
Your code works for me as-is. Is it possible that changes to residual_reports have not been committed yet?
What Mysql version do you use? It seems that they have similar problems before with enum values
http://bugs.mysql.com/bug.php?id=24985