MYSQL: Cannot add or update a child row: a foreign key constraint fails - mysql

I am getting the error:
Cannot add or update a child row: a foreign key constraint fails (mydb/requests, CONSTRAINT requests_ibfk_5 FOREIGN KEY (fixture_id) REFERENCES fixtures (fix_id) ON UPDATE CASCADE ON DELETE CASCADE)
I have the following table structure:
CREATE TABLE IF NOT EXISTS `requests` (
`request_id` int(11) unsigned NOT NULL auto_increment,
`fixture_id` int(11) unsigned NOT NULL,
`user_id` int(11) unsigned NOT NULL,
`date_added` datetime NOT NULL,
`date_modified` datetime default NULL,
PRIMARY KEY (`request_id`),
UNIQUE KEY `fixture_id_2` (`fixture_id`,`user_id`),
KEY `user_id` (`user_id`),
KEY `date_added` (`date_added`),
KEY `fixture_id` (`fixture_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=17 ;
CREATE TABLE IF NOT EXISTS `fixtures` (
`id` int(11) unsigned NOT NULL auto_increment,
`fix_id` int(11) unsigned NOT NULL default '0',
`fixture_date` date default NULL,
`kickoff` time default NULL,
`venue` varchar(35) default NULL,
`home_score` tinyint(4) default NULL,
`away_score` tinyint(4) default NULL,
`date_added` datetime default NULL,
`date_modified` datetime default NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `fix_id` (`fix_id`),
KEY `fixture_date` (`fixture_date`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=383 ;
ALTER TABLE `requests`
ADD CONSTRAINT `requests_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`) ON DELETE CASCADE,
ADD CONSTRAINT `requests_ibfk_5` FOREIGN KEY (`fixture_id`) REFERENCES `fixtures` (`fix_id`) ON DELETE CASCADE ON UPDATE CASCADE;
If I update a record on the fix_id field the parent table (fixtures), that has a shared id (fixture_id) in the child table (requests) I get the above error.
I cannot see why this integrity constraint is failing. Both tables already have the correct data it should cascade through?
Any help greatly appreciated.

This was all my own error. I had two foreign constraints on the same field in reality. I just needed to take one off.

This error occurs due to the reference of other table, in both tables same id's/data should exist. If not please use where conditions to remove not existing data.
example
update tablename a set = 'field' (select field from othertable b) where a.data = b.data;

Related

Foreign key constraint fails when I want delete table

When I am trying
drop tables users;
It shows error: Cannot delete or update a parent row: a foreign key constraint fails
Here are my tables:
CREATE TABLE `events` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(128) NOT NULL,
`users_id` int(11) NOT NULL,
`capacity` int(64) NOT NULL,
`event_date` datetime NOT NULL,
`text` text CHARACTER SET utf8 COLLATE utf8_czech_ci,
`last_edit` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `users_id` (`users_id`),
CONSTRAINT `events_ibfk_5` FOREIGN KEY (`users_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL,
`role` enum('admin','member','guest','registered') NOT NULL DEFAULT 'registered',
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `users_data` (
`id` int(120) NOT NULL AUTO_INCREMENT,
`users_id` int(11) DEFAULT NULL,
`name` varchar(50) NOT NULL,
`username` varchar(50) NOT NULL,
`phone_number` varchar(25) NOT NULL,
PRIMARY KEY (`id`),
KEY `users_id` (`users_id`),
CONSTRAINT `users_data_ibfk_5` FOREIGN KEY (`users_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `user_matches` (
`user_id` int(120) NOT NULL,
`match_id` int(11) NOT NULL,
KEY `user_id` (`user_id`),
KEY `match_id` (`match_id`),
CONSTRAINT `user_matches_ibfk_4` FOREIGN KEY (`user_id`) REFERENCES `users_data` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `user_matches_ibfk_5` FOREIGN KEY (`match_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I think I did wrong foreign key but I am not sure how to change it correctly. Thank you for your any advice.
When you submit drop table users MySQL checks for referential integrity constraints violation when the deletion is about to be committed. This check fails because you have defined the following constraint of events:
CONSTRAINTevents_ibfk_5FOREIGN KEY (users_id) REFERENCESusers(id) ON DELETE CASCADE ON UPDATE CASCADE
and at the same time on the events table the users_id field cannot be NULL. Therefore, upon dropping the table, the users_id is set to NULL which fails during commit. One possible way to work around this problem is to remove the NOT NULL constraint on the users_id field on the events table.

MySQL error when update foreign key

I have 2 tables following below:
CREATE TABLE `queststatus` (
`queststatusid` int(10) unsigned NOT NULL AUTO_INCREMENT,
`characterid` int(11) NOT NULL DEFAULT '0',
`quest` int(6) NOT NULL DEFAULT '0',
`status` tinyint(4) NOT NULL DEFAULT '0',
`time` int(11) NOT NULL DEFAULT '0',
`forfeited` int(11) NOT NULL DEFAULT '0',
`customData` varchar(255) DEFAULT NULL,
PRIMARY KEY (`queststatusid`),
KEY `characterid` (`characterid`),
CONSTRAINT `queststatus_ibfk_1` FOREIGN KEY (`characterid`) REFERENCES `characters` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2148654268 DEFAULT CHARSET=utf8 ROW_FORMAT=FIXED
and
CREATE TABLE `queststatusmobs` (
`queststatusmobid` int(10) unsigned NOT NULL AUTO_INCREMENT,
`queststatusid` int(10) unsigned NOT NULL DEFAULT '0',
`mob` int(11) NOT NULL DEFAULT '0',
`count` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`queststatusmobid`),
KEY `queststatusid` (`queststatusid`),
CONSTRAINT `queststatusmobs_ibfk_1` FOREIGN KEY (`queststatusid`) REFERENCES `queststatus` (`queststatusid`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
So,when I update the queststatusid of table queststatus, I use these command because the queststatusid reached the maximum of INT:
SET foreign_key_checks = 1;
SET #newid=0;
UPDATE queststatus SET queststatusid=(#newid:=#newid+1) ORDER BY queststatusid;
this command should makes queststatusid of table queststatusmobs change when queststatusid of of table queststatus update, but it doesn't.
It shows:
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`twms`.`queststatus`, CONSTRAINT `queststatus_ibfk_1` FOREIGN KEY (`characterid`) REFERENCES `characters` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)
I have deleted all useless foreign key which not in queststatus by using this command first:
DELETE FROM queststatusmobs WHERE queststatusid not in (SELECT queststatusid FROM queststatus);
How can I solve this problem?
You didn't have that particular id is not available on your characters table.
First you insert characters table id and used that id as a foreign key on queststatus table.
Or
Remove the foreign key reference from queststatus.
You might not able to change the id if you have a foreign key against it as it validate vice versa. You will either have to disable the foreign key checks or consider about changing the data type to BIGINT. That will be the most appropriate thing instead of trying to modifying the data.
To disable the foreign key check:
SET foreign_key_checks = 0;
Or else you can drop and create the foreign key

Error 1215: Cannot add foreign key constraint SQL Statement

Not sure why I am still encountering the issue "Error 1215" wherein they have the same data type and parent table is in primary key.
child table:
CREATE TABLE `customer_notice_type` (
`CUSTOMER_NOTICE_TYPE_ID` int(11) NOT NULL AUTO_INCREMENT,
`CUSTOMER_ID` int(11) NOT NULL,
`CUSTOMER_NOTICE_TYPE_NAME` varchar(50) NOT NULL,
`SYSTEM_NOTICE_TYPE_ID` int(11) NOT NULL,
`STATUS` char(1) NOT NULL,
`CREATED_BY` varchar(50) NOT NULL,
`CREATED_DATE` datetime NOT NULL,
`MODIFIED_BY` varchar(50) DEFAULT NULL,
`MODIFIED_DATE` datetime DEFAULT NULL,
PRIMARY KEY (`CUSTOMER_NOTICE_TYPE_ID`),
KEY `fk_customer_id_customer_notice_type_idx` (`CUSTOMER_ID`),
CONSTRAINT `fk_customer_id_customer_notice_type` FOREIGN KEY (`CUSTOMER_ID`) REFERENCES `customer` (`CUSTOMER_ID`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=494 DEFAULT CHARSET=latin1;
parent table:
CREATE TABLE `system_notice_type` (
`SYSTEM_NOTICE_TYPE_ID` int(11) NOT NULL,
`SYSTEM_NOTICE_TYPE_NAME` varchar(45) NOT NULL,
`LINE_OF_BUSINESS_ID` int(11) NOT NULL,
`STATUS` char(1) NOT NULL,
PRIMARY KEY (`SYSTEM_NOTICE_TYPE_ID`)
) ENGINE=MyISAM AUTO_INCREMENT=16 DEFAULT CHARSET=latin1;
SQL script to create Foreign Key:
ALTER TABLE `fexpress`.`customer_notice_type`
ADD CONSTRAINT `fk_system_notice_type_customer_notice_type`
FOREIGN KEY (`SYSTEM_NOTICE_TYPE_ID`)
REFERENCES `fexpress`.`system_notice_type` (`SYSTEM_NOTICE_TYPE_ID`)
ON DELETE CASCADE ON UPDATE CASCADE;
You have two potential problems. First, the alter table statement references fexpress. This may or may not be the correct schema for the table. So, that is one potential problem.
The second real problem is the constraint defined in the child table:
CONSTRAINT `fk_customer_id_customer_notice_type` FOREIGN KEY (`CUSTOMER_ID`) REFERENCES `customer`(`CUSTOMER_ID`) ON DELETE CASCADE ON UPDATE CASCADE
The parent table is not yet defined, so it generates an error.
Removing this row and adjusting the schema name results in working code, as in this SQL Fiddle.

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;

MySQL error when trying to truncate table

I'm having problems to truncate a table on the MySQL Server 5.5.
The table I'm trying to truncate has a column that serves as a foreign key in another table.
The CREATE TABLE of both tables involved is as it follows:
CREATE TABLE `tbluser` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`creationDate` datetime NOT NULL,
`creationUserId` int(11) NOT NULL,
`updateDate` datetime NOT NULL,
`updateUserId` int(11) NOT NULL,
`lastAccess` datetime NOT NULL,
`enabled` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`),
UNIQUE KEY `email_UNIQUE` (`email`),
KEY `FK_tbluser_creationUserId` (`creationUserId`),
KEY `FK_tbluser_updateUserId` (`updateUserId`),
CONSTRAINT `FK_tbluser_updateUserId` FOREIGN KEY (`updateUserId`) REFERENCES `tbluser` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `FK_tbluser_creationUserId` FOREIGN KEY (`creationUserId`) REFERENCES `tbluser` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
CREATE TABLE `tblpost` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`content` mediumtext NOT NULL,
`creationDate` datetime NOT NULL DEFAULT '1901-01-01 00:00:00',
`creationUserId` int(11) NOT NULL,
`updateDate` datetime NOT NULL DEFAULT '1901-01-01 00:00:00',
`updateUserId` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_tblpost_creationUserId` (`creationUserId`),
KEY `FK_tblpost_updateUserId` (`updateUserId`),
CONSTRAINT `FK_tblpost_updateUserId` FOREIGN KEY (`updateUserId`) REFERENCES `tbluser` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `FK_tblpost_creationUserId` FOREIGN KEY (`creationUserId`) REFERENCES `tbluser` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Please note that all the constraints are both set to DELETE and UPDATE ON CASCADE.
When I try to TRUNCATE the table:
TRUNCATE TABLE `<databasename>`.`tbluser`;
I receive the following error message:
Cannot truncate a table referenced in a foreign key constraint
(`<databasename>`.`tblpost`,
CONSTRAINT `FK_tblpost_updateUserId`
FOREIGN KEY (`updateUserId`)
REFERENCES `<databasename>`.`tbluser` (`id`))
In addition to this information, there is the fact that when the action above is attempted on a MySQL Server 5.1, it works!
Does anyone have an idea of why this is happening?
Check here . That makes sense that TRUNCATE TABLE raises an error in such cases; the bad thing that it's not documented.