Error 1452 Foreign Key Fails - mysql

I am getting a 1452 error from MySQL. Here is the SQL I used to INSERT
INSERT INTO `Quote` (`QTE_id`, `USR_id`, `QTE_total`, `QTE_desc`, `QTE_dateCreated`, `QTE_dateModified`,`QTE_name`, `QTE_status`)
VALUES
(39, 2, NULL, 'desc', '2013-11-19 00:00:00', '2013-11-19 11:22:49', 'test', 'Active');
Cannot add or update a child row: a foreign key constraint fails (`dbNAME`.`Quote`, CONSTRAINT `USR_id1` FOREIGN KEY (`USR_id`) REFERENCES `users` (`USR_id`))
I am positive that the USR_id I am trying to put into the Quote table exists. Any ideas? A lot of the other questions on Stack Overflow did not answer my question.
Here is the Create syntax for the following tables I am trying to insert and relate (generated from Workbench):
CREATE TABLE `Quote` (
`QTE_id` int(11) NOT NULL AUTO_INCREMENT,
`USR_id` int(11) DEFAULT NULL,
`QTE_total` decimal(7,2) DEFAULT NULL,
`QTE_desc` text,
`QTE_dateCreated` timestamp NULL DEFAULT NULL,
`QTE_dateModified` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`QTE_name` varchar(255) DEFAULT NULL,
`QTE_status` varchar(30) DEFAULT NULL,
PRIMARY KEY (`QTE_id`),
KEY `USR_id1` (`USR_id`),
CONSTRAINT `USR_id1` FOREIGN KEY (`USR_id`) REFERENCES `users` (`USR_id`)
) ENGINE=InnoDB AUTO_INCREMENT=39 DEFAULT CHARSET=utf8;
And the User Table:
CREATE TABLE `Users` (
`USR_id` int(11) NOT NULL AUTO_INCREMENT,
`MGR_id` int(11) NOT NULL DEFAULT '0'
`REP_id` int(11) NOT NULL,
`USR_name` varchar(255) NOT NULL,
`USR_login` varchar(255) NOT NULL,
`USR_dateModified` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`USR_dateCreated` datetime NOT NULL,
`USR_role` enum('Salesperson','Manager') DEFAULT NULL,
PRIMARY KEY (`USR_id`,`MGR_id`,`REP_id`),
KEY `MGR_id_idx` (`MGR_id`),
KEY `REP_id_idx` (`REP_id`),
KEY `USR_login` (`USR_login`),
CONSTRAINT `MGR_id` FOREIGN KEY (`MGR_id`) REFERENCES `users` (`USR_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `REP_id` FOREIGN KEY (`REP_id`) REFERENCES `representative` (`REP_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8

I had to do a few small changes (change the users to Users, add a ',' at the end of line that defines MGR_id, remove the constraint for REP_id) to make the two CREATEs to work.
Here are the exact CREATEs:
CREATE TABLE `Users` (
`USR_id` int(11) NOT NULL AUTO_INCREMENT,
`MGR_id` int(11) NOT NULL DEFAULT '0',
`REP_id` int(11) NOT NULL,
`USR_name` varchar(255) NOT NULL,
`USR_login` varchar(255) NOT NULL,
`USR_dateModified` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`USR_dateCreated` datetime NOT NULL,
`USR_role` enum('Salesperson','Manager') DEFAULT NULL,
PRIMARY KEY (`USR_id`,`MGR_id`,`REP_id`),
KEY `MGR_id_idx` (`MGR_id`),
KEY `REP_id_idx` (`REP_id`),
KEY `USR_login` (`USR_login`),
CONSTRAINT `MGR_id` FOREIGN KEY (`MGR_id`) REFERENCES `Users` (`USR_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
CREATE TABLE `Quote` (
`QTE_id` int(11) NOT NULL AUTO_INCREMENT,
`USR_id` int(11) DEFAULT NULL,
`QTE_total` decimal(7,2) DEFAULT NULL,
`QTE_desc` text,
`QTE_dateCreated` timestamp NULL DEFAULT NULL,
`QTE_dateModified` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`QTE_name` varchar(255) DEFAULT NULL,
`QTE_status` varchar(30) DEFAULT NULL,
PRIMARY KEY (`QTE_id`),
KEY `USR_id1` (`USR_id`),
CONSTRAINT `USR_id1` FOREIGN KEY (`USR_id`) REFERENCES `Users` (`USR_id`)
) ENGINE=InnoDB AUTO_INCREMENT=39 DEFAULT CHARSET=utf8;
With that in place the following two INSERTs worked:
mysql> INSERT INTO `Users` (`USR_id`, `MGR_id`) VALUES(2, 2);
Query OK, 1 row affected, 4 warnings (0.22 sec)
mysql> INSERT INTO `Quote` (`QTE_id`, `USR_id`, `QTE_total`, `QTE_desc`, `QTE_dateCreated`, `QTE_dateModified`,`QTE_name`, `QTE_status`) VALUES (39, 2, NULL, 'desc', '2013-11-19 00:00:00', '2013-11-19 11:22:49', 'test', 'Active');
Query OK, 1 row affected (0.22 sec)
I hope this helps.

Related

MySQL relationship with 2 table

I have two tables:
CREATE TABLE `companies` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`industry_id` int(11) DEFAULT NULL,
... other fields ...
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
and:
CREATE TABLE `industries` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I tried to add a foreign key to the second table:
ALTER TABLE industries ADD FOREIGN KEY (id) REFERENCES companies(industry_id) ON DELETE RESTRICT;
But I got next error:
Cannot add foreign key constraint
How can I add right fkey?
I suppose you've done it wrong. Primary key can't be Foreign Key.
Let's make little changes, which can give you the same value
ALTER TABLE companies ADD FOREIGN KEY (industry_id) REFERENCES industries(id) ON DELETE RESTRICT;

Cannot delete foreign key constraint fails

When I try to delete the question from the test, the sql show :
`Cannot delete or update a parent row: a foreign key constraint fails (`oes`.`studentquestion`,
CONSTRAINT `studentquestion_ibfk_2` FOREIGN KEY (`testid`, `qnid`) REFERENCES `question`
(`testid`, `qnid`))`
Here will be my table:
student table
CREATE TABLE `student` (
`stdid` bigint(20) NOT NULL,
`subid` int(11) NOT NULL,
`stdname` varchar(40) default NULL,
`stdpassword` varchar(40) default NULL,
`emailid` varchar(40) default NULL,
`contactno` varchar(20) default NULL,
`address` varchar(40) default NULL,
`city` varchar(40) default NULL,
`pincode` varchar(20) default NULL,
PRIMARY KEY (`stdid`),
UNIQUE KEY `stdname` (`stdname`),
UNIQUE KEY `emailid` (`emailid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
studentquestion table
CREATE TABLE `studentquestion` (
`stdid` bigint(20) NOT NULL default '0',
`testid` bigint(20) NOT NULL default '0',
`qnid` int(11) NOT NULL default '0',
`answered` enum('answered','unanswered','review') DEFAULT NULL,
`stdanswer` enum('optiona','optionb','optionc','optiond') DEFAULT NULL,
PRIMARY KEY (`stdid`,`testid`,`qnid`),
KEY `testid` (`testid`,`qnid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
studenttest table
`stdid` bigint(20) NOT NULL default '0',
`testid` bigint(20) NOT NULL default '0',
`starttime` timestamp NOT NULL default CURRENT_TIMESTAMP,
`endtime` timestamp NOT NULL default '0000-00-00 00:00:00',
`correctlyanswered` int(11) default NULL,
`status` enum('over','inprogress') default NULL,
PRIMARY KEY (`stdid`,`testid`),
KEY `testid` (`testid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
question table
CREATE TABLE `question` (
`testid` bigint(20) NOT NULL default '0',
`qnid` int(11) NOT NULL default '0',
`question` varchar(500) default NULL,
`optiona` varchar(100) DEFAULT NULL,
`optionb` varchar(100) DEFAULT NULL,
`optionc` varchar(100) DEFAULT NULL,
`optiond` varchar(100) DEFAULT NULL,
`correctanswer` enum ('optiona','optionb','optionc','optiond') DEFAULT NULL,
`marks` int(11) DEFAULT NULL,
PRIMARY KEY (`testid`,`qnid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
test table
CREATE TABLE `test` (
`testid` bigint(20) NOT NULL,
`testname` varchar(30) NOT NULL,
`testdesc` varchar(100) default NULL,
`testdate` date default NULL,
`testtime` time default NULL,
`subid` int(11) default NULL,
`testfrom` timestamp NOT NULL default CURRENT_TIMESTAMP,
`testto` timestamp NOT NULL default '0000-00-00 00:00:00',
`duration` int(11) default NULL,
`totalquestions` int(11) default NULL,
`attemptedstudents` bigint(20) DEFAULT NULL,
`testcode` varchar(40) NOT NULL,
`tcid` bigint(20) default NULL,
`minimunscore` int(11) NOT NULL,
PRIMARY KEY (`testid`),
UNIQUE KEY `testname` (`testname`),
KEY `test_fk1` (`subid`),
KEY `test_fk2` (`tcid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
subject table
CREATE TABLE `subject` (
`subid` int(11) NOT NULL,
`subname` varchar(40) default NULL,
`subdesc` varchar(100) default NULL,
`tcid` bigint(20) default NULL,
PRIMARY KEY (`subid`),
UNIQUE KEY `subname` (`subname`),
KEY `subject_fk1` (`tcid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `studentquestion`
ADD CONSTRAINT `studentquestion_ibfk_1` FOREIGN KEY (`stdid`) REFERENCES `student`
(`stdid`),
ADD CONSTRAINT `studentquestion_ibfk_2` FOREIGN KEY (`testid`, `qnid`) REFERENCES `question`
(`testid`, `qnid`);
ALTER TABLE `studenttest`
ADD CONSTRAINT `studenttest_ibfk_1` FOREIGN KEY (`stdid`) REFERENCES `student` (`stdid`),
ADD CONSTRAINT `studenttest_ibfk_2` FOREIGN KEY (`testid`) REFERENCES `test` (`testid`);
ALTER TABLE `question`
ADD CONSTRAINT `question_ibfk_1` FOREIGN KEY (`testid`) REFERENCES `test` (`testid`);
ALTER TABLE `test`
ADD CONSTRAINT `test_fk1` FOREIGN KEY (`subid`) REFERENCES `subject` (`subid`),
ADD CONSTRAINT `test_fk2` FOREIGN KEY (`tcid`) REFERENCES `testconductor` (`tcid`);
ALTER TABLE `subject`
ADD CONSTRAINT `subject_fk1` FOREIGN KEY (`tcid`) REFERENCES `testconductor` (`tcid`);
INSERT INTO `adminlogin` VALUES ('001','root','root');
INSERT INTO `studenttest` (`stdid`, `testid`, `starttime`, `endtime`, `correctlyanswered`,
`status`) VALUES
(1, 1, '2014-10-15 09:11:24', '2014-10-15 09:21:24', 0, 'over');
INSERT INTO `subject` (`subid`, `subname`, `subdesc`, `tcid`) VALUES
(1, 'fref', 'few', NULL);
INSERT INTO `test` (`testid`, `testname`, `testdesc`, `testdate`, `testtime`, `subid`,
`testfrom`, `testto`, `duration`, `totalquestions`, `attemptedstudents`, `testcode`, `tcid`)
VALUES
(1, 'gregre', 'greger', '2014-10-15', '17:08:16', 1, '2014-10-15 03:08:16', '2014-10-16
15:59:59', 10, 2, 0, '.ȁ', NULL);
When the student has complete the test, then the question will not be able to delete. Neither the test or subject.
It is because the studentquestion table will be left with a foreign key that points to a non existent record. You'll either need to remove rows which have a foreign key to the record you want to delete or, alternatively set up CASCADE rules so that when parent rows are deleted action can be taken.

mysql cannot add foreign key for unknown reason

I cannot a add a foreign key constraint. the sql i m running is -
ALTER TABLE image_shout ADD CONSTRAINT `fk_image` FOREIGN KEY (image_id)
REFERENCES images(image_id);
the collation and the data types( int(10) ) are same in the two tables.
mysql says -
Error Code: 1215. Cannot add foreign key constraint
The images table structure -
CREATE TABLE `images` (
`image_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`image_name` varchar(100) CHARACTER SET latin1 NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`caption` varchar(450) CHARACTER SET latin1 DEFAULT NULL,
`image_visibility` int(10) unsigned NOT NULL,
`album_id` int(10) unsigned NOT NULL,
`album_view` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`album_thumb_view` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`image_id`),
KEY `Index_2` (`album_id`),
CONSTRAINT `FK_images_1` FOREIGN KEY (`album_id`) REFERENCES `photo_album` (`Album_ID`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=4314 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
The image_shout table -
CREATE TABLE `image_shout` (
`auto_id` int(11) NOT NULL AUTO_INCREMENT,
`shout_id` int(11) DEFAULT NULL,
`image_id` int(10) DEFAULT NULL,
PRIMARY KEY (`auto_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1132 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
UPDATE -
The new error after changing the image_id column to unsigned is -
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails
(`void`.`#sql-36b_7285`, CONSTRAINT `fk_image` FOREIGN KEY (`image_id`)
REFERENCES `images` (`image_id`) ON DELETE SET NULL ON UPDATE CASCADE)
Regards
Is because the image_id in table images is defined as unsigned
`image_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
and in image_shout not
`image_id` int(10) DEFAULT NULL,
Change both columns to the same data type and it should work.
The problem is below. According to the documentation, a foreign key must be indexed. Further, a foreign key should reference the KEY of another table. Not just a column. Try using auto_id as the constraint if you don't wish to change your table structure.
Please see MySQL Documentation for the list of requirements of a Foreign Key constraint.
CREATE TABLE `image_shout` (
`auto_id` int(11) NOT NULL AUTO_INCREMENT,
`shout_id` int(11) DEFAULT NULL,
`image_id` int(10) DEFAULT NULL,
PRIMARY KEY (`auto_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1132 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Foreign key constraint fails even if parent row is present

I have following 2 tables.
CREATE TABLE `RuleEntity` (
`rule_id` bigint(20) NOT NULL,
`action_word` varchar(255) DEFAULT NULL,
`condition_word` varchar(255) DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`ruleGUID` varchar(255) NOT NULL,
`rule_type` varchar(255) DEFAULT NULL,
`caseflag` tinyint(1) NOT NULL DEFAULT '0',
`globalflag` tinyint(1) NOT NULL DEFAULT '1',
`multilineflag` tinyint(1) NOT NULL DEFAULT '1',
`isDefault` tinyint(1) DEFAULT '0',
PRIMARY KEY (`rule_id`),
UNIQUE KEY `ruleGUID` (`ruleGUID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
CREATE TABLE `PreProcessorRule` (
`id` bigint(20) NOT NULL,
`rank` int(11) DEFAULT NULL,
`rule_rule_id` bigint(20) DEFAULT NULL,
`defaultRuleGUID` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FK4BD420EB4273A655` (`rule_rule_id`),
CONSTRAINT `FK4BD420EB4273A655` FOREIGN KEY (`rule_rule_id`) REFERENCES `RuleEntity` (`rule_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
I am trying to insert 1 row in RuleEntiy and another in PreprocessorRule. But it fails with foreign key constraint.
INSERT INTO `RuleEntity` (`rule_id`,`action_word`,`condition_word`,`description`,`caseflag`,`globalflag`,`multilineflag`,`name`,`ruleGUID`,`rule_type`, `isDefault`) VALUES ( '1',' ','[^\\x00-\\x7F]','HF Default Rule: Removes Non-ASCII Character.',1,1,1,'HF: Non-ASCII Remover','1157B568665E08','CUSTOM', 1);
Query OK, 1 row affected (0.02 sec)
INSERT INTO `HFP`.`PreProcessorRule` (`id`, `rank`, `rule_rule_id`) VALUES ('1', '0', '1');
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`HFP`.`PreProcessorRule`, CONSTRAINT `FK4BD420EB4273A655` FOREIGN KEY (`rule_rule_id`) REFERENCES `RuleEntity` (`rule_id`))
I ran same sql on local MySQL 5.1 on MAC OS X 10.9. It worked. Now I am trying to run it on the Amazon RDS MySQL where I get this error.
Kindly let me know what is going wrong?

Put unique index across more than one table

I have run into a problem where the easiest solution would be to add a unique index that goes across multiple tables in mysql. Is this possible?
For the purpose of this question I will have three tables; status, tracks and events. The status and tracks tables both have an auto incrementing ID (T_ID or S_ID) in. Information from them is added to the events table with a trigger. The problem is that there could be the same auto incrementing ID in tracks and status, this means that their could be the same ID more than once in events.
tracks;
CREATE TABLE `tracks` (
`ID` int(11) NOT NULL,
`url` varchar(200) COLLATE latin1_general_ci NOT NULL,
`name` varchar(100) COLLATE latin1_general_ci NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
`T_ID` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`T_ID`),
UNIQUE KEY `url` (`url`),
UNIQUE KEY `T_ID` (`T_ID`),
KEY `ID` (`ID`),
CONSTRAINT `tracks_ibfk_1` FOREIGN KEY (`ID`) REFERENCES `members` (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci
status
CREATE TABLE `status` (
`ID` int(11) NOT NULL,
`status` varchar(300) COLLATE latin1_general_ci NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
`S_ID` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`S_ID`),
UNIQUE KEY `S_ID` (`S_ID`),
KEY `ID` (`ID`),
CONSTRAINT `status_ibfk_1` FOREIGN KEY (`ID`) REFERENCES `artists` (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci
events
CREATE TABLE `events` (
`ID` int(11) NOT NULL,
`action` varchar(100) COLLATE latin1_general_ci NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
`E_ID` int(11) NOT NULL,
KEY `ID` (`ID`),
CONSTRAINT `events_ibfk_1` FOREIGN KEY (`ID`) REFERENCES `members` (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci COMMENT='This table shows what the artist has done and is used feed'
Agreed, you cannot have an index across multiple tables.
However, consider changing your schema by adding a "source" column to your event table and making a unique constraint on the combination of the source and the foreign key. This would prevent duplicate keys being inserted from the same source.