Click here to Skip to main content
15,559,275 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have these tables:
SQL
CREATE TABLE `faculty_personal_info` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `Designation` varchar(30) NOT NULL,
  `First_Name` varchar(20) NOT NULL,
  `Middle_Name` varchar(20) DEFAULT NULL,
  `Last_Name` varchar(20) NOT NULL,
  `Date_of_Birth` date NOT NULL,
  `Address` varchar(100) NOT NULL,
  `City` varchar(30) NOT NULL,
  `Pincode` int(11) NOT NULL,
  `Email` varchar(40) NOT NULL,
  `Contact_Number` int(11) NOT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8

SQL
CREATE TABLE `faculty_edu_qual` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `faculty_id` int(11) NOT NULL,
  `Degree` varchar(15) NOT NULL,
  `Specialisation` varchar(40) NOT NULL,
  `University` varchar(40) NOT NULL,
  `Grade` varchar(10) NOT NULL,
  `Year_of_Passing` int(11) NOT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  KEY `FK_faculty_edu_qual_faculty_personal_info` (`faculty_id`),
  CONSTRAINT `FK_faculty_edu_qual_faculty_personal_info` FOREIGN KEY (`faculty_id`) REFERENCES `faculty_personal_info` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8

I have inserted a record in the faculty personal info table successfully. Now when I use this commands,
set @faculty_id = last_insert_id();
insert into faculty_equ_qual values('1',@faculty_id,'B.Tech','CSE','PEC','S','2015');
I get this error:
VB
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint f
ails (`faculty_student`.`faculty_edu_qual`, CONSTRAINT `FK_faculty_edu_qual_facu
lty_personal_info` FOREIGN KEY (`faculty_id`) REFERENCES `faculty_personal_info`
 (`id`) ON DELETE CASCADE ON UPDATE CA)
Posted

1 solution

If you are inserting record into faculty_personal_info table first and then immediately thereafter you are inserting into faculty_edu_qual table the query should work. Verify that you are not running any insert queries in between.

In case you are inserting record sequentially and still getting the same error, then please make sure that you have identity value set for the column else you will be getting null value for variable @faculty_id
 
Share this answer
 
v2
Comments
SubhamSoni123 21-Oct-13 8:42am    
First I am inserting a dummy record using the mysql insert query in faculty_personal_info and then only passing the last inserted id into the faculty_edu_qual table...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900