MySQL error when update foreign key - mysql

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

Related

foreign key constraint field set to NULL not working

I want to allow NULL values to a field with foreign key constraint set.
Here's the table schema:
CREATE TABLE `internal_team_head` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`internal_team_id` int(11) NOT NULL,
`users_id` int(11) NOT NULL DEFAULT '0',
`type` enum('lead','project_manager') NOT NULL,
`updated_by` int(6) DEFAULT NULL,
`updated_on` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`,`internal_team_id`,`users_id`,`type`),
KEY `fk_internal_team_has_users_users1_idx` (`users_id`),
KEY `fk_internal_team_has_users_internal_team1_idx` (`internal_team_id`),
CONSTRAINT `fk_internal_team_has_users_internal_team1` FOREIGN KEY (`internal_team_id`) REFERENCES `internal_team` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=69 DEFAULT CHARSET=utf8
Now I want to change users_id to allow NULL values and default to NULL.
ALTER TABLE `internal_team_head` CHANGE `users_id` `users_id` INT(11) NULL DEFAULT NULL;
The Alter query executes successfully but users_id Null attribute is still set to No and default value set to 0.
How do I enforce the changes?
Dropping foreign key constraint first, then running your alter statement should work. You can add the constraint back again after that.

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

CREATE TABLE `class` (
`class_id` int(11) NOT NULL AUTO_INCREMENT,
`section_name` varchar(50) NOT NULL,
`class_alias` varchar(200) NOT NULL,
`grading_scheme` int(11) NOT NULL DEFAULT '0',
`year` year(4) NOT NULL,
`grade_calc_method_id` varchar(20) DEFAULT NULL,
PRIMARY KEY (`class_id`)
) ENGINE=InnoDB AUTO_INCREMENT=48819 DEFAULT CHARSET=latin1;
CREATE TABLE `teachers` (
`teacher_id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`teacher_subject` varchar(20) NOT NULL DEFAULT 'None',
PRIMARY KEY (`teacher_id`),
KEY `user_id` (`user_id`,`school_id`)
) ENGINE=InnoDB AUTO_INCREMENT=48606 DEFAULT CHARSET=latin1;
CREATE TABLE `teacher_classes` (
`teacher_class_id` int(11) NOT NULL AUTO_INCREMENT,
`teacher_id` int(11) NOT NULL,
`class_id` int(11) NOT NULL,
PRIMARY KEY (`teacher_class_id`),
UNIQUE KEY `teacher_id_class_id` (`teacher_id`,`class_id`),
KEY `teacher_id` (`teacher_id`,`class_id`)
) ENGINE=InnoDB AUTO_INCREMENT=46707 DEFAULT CHARSET=latin1;
Trying to insure data consistency between the tables by using foreign key so that the DBMS can check for errors.I have another junction table teacher_classes
Here is my query to add foreign keys constraint
ALTER TABLE teacher_classes
ADD CONSTRAINT `tc_fk_class_id` FOREIGN KEY (`class_id`)
REFERENCES class (`class_id`) ON UPDATE NO ACTION ON DELETE NO ACTION,
ADD CONSTRAINT `tc_fk_teacher_id` FOREIGN KEY (`teacher_id`)
REFERENCES teachers (`teacher_id`) ON UPDATE NO ACTION ON DELETE NO ACTION;
've seen the other posts on this topic, but no luck, getting following error.
Cannot add or update a child row: a foreign key constraint fails
(DB_NAME.#sql-403_12, CONSTRAINT
tc_fk_teacher_id FOREIGN KEY (teacher_id) REFERENCES teachers
(teacher_id) ON DELETE NO ACTION ON UPDATE NO ACTION)
Too late to Answer. I just had the same problem the solution is easy.
You're getting this error because you're trying to or UPDATE a row to teacher_classes doesn't match the id in table teachers.
A simple solution is disable foreign key checks before performing any operation on the table.
SET FOREIGN_KEY_CHECKS = 0;
After you are done with the table enable it again.
SET FOREIGN_KEY_CHECKS = 1;
Or you can remove not null constraint and insert a NULL value in it.
That's most probably the column definition doesn't match properly. For table teachers the PK column definition is as below.
`teacher_id` int(11) NOT NULL AUTO_INCREMENT
Make sure you have the same definition in your child table teacher_classes

mysql - foreign key cascade update

I have a question about how to update a field on cascade with a second field as constraint.
The structure is this (I removed the unnecessary columns):
Table nodes with columns idNode and idDimension (together they form the primary key).
Table forces with columns idForce (PK), idNode (foreign key to nodes.idNode) and idDimension.
Cascade update and delete on everything.
The problem in this structure that it seems to appear is this:
If in nodes I have an entry like (1, 1) and one like (1, 2) and in forces (1, 1, 1) and (1, 1, 2) and I update or delete first entry from nodes both entries in forces will be affected.
I need to affect only the one that also has the corresponding idDimension. How can I modify current structure to do that?
Edit: Tables - Nodes:
CREATE TABLE IF NOT EXISTS `nodes` (
`idNode` varchar(11) NOT NULL,
`idDimension` int(10) unsigned NOT NULL,
`idNetwork` int(10) unsigned NOT NULL DEFAULT '0',
`level` int(11) unsigned NOT NULL DEFAULT '0',
`energy` bigint(20) DEFAULT NULL,
`resources` bigint(20) unsigned NOT NULL DEFAULT '0',
`x` int(11) NOT NULL,
`y` int(11) NOT NULL,
`name` varchar(20) DEFAULT NULL,
`order` tinyint(3) DEFAULT '0' COMMENT 'energy 0\nassemble 1\nupgrade 2',
`core` tinyint(1) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`idNode`,`idDimension`),
KEY `network_dimension` (`idDimension`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Node table';
Forces:
CREATE TABLE IF NOT EXISTS `forces` (
`idForce` bigint(10) unsigned NOT NULL AUTO_INCREMENT,
`idNode` varchar(11) NOT NULL,
`idDimension` int(10) unsigned NOT NULL,
`drones` bigint(20) DEFAULT NULL,
`stance` tinyint(3) DEFAULT NULL COMMENT '0 - defense\n1 - neutral\n2 - attack \n\nIf planet is parano and you are not allied to owner you can only be in attack.\n\nIf owner is allied you can only be in defense or neutral.\n\nIf you are owner you can only be in defense.',
`order` tinyint(3) DEFAULT '0' COMMENT 'extract energy 1\nbuild node 2\nreplicate 3\nmove 4',
`value` text,
PRIMARY KEY (`idForce`),
KEY `idNode` (`idNode`,`idDimension`),
KEY `idDimension` (`idDimension`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
--
-- Constraints for table forces
ALTER TABLE `forces`
ADD CONSTRAINT `forces_ibfk_2` FOREIGN KEY (`idDimension`) REFERENCES `nodes` (`idDimension`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `fk_forces_nodes1` FOREIGN KEY (`idNode`, `idDimension`) REFERENCES `nodes` (`idNode`, `idDimension`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `forces_ibfk_1` FOREIGN KEY (`idNode`) REFERENCES `nodes` (`idNode`) ON DELETE CASCADE ON UPDATE CASCADE;
My constraints are not working as I would like so feel free to ignore them :).
There are two strange foreign key (forces_ibfk_1 and forces_ibfk_2) which refers to non unique fields. Remove them -
ALTER TABLE forces DROP FOREIGN KEY forces_ibfk_1;
ALTER TABLE forces DROP FOREIGN KEY forces_ibfk_2;
Then recreate fk_forces_nodes1 that refers to unique pair of fields with CASCADE action option -
ALTER TABLE forces
DROP FOREIGN KEY fk_forces_nodes1;
ALTER TABLE orces
ADD CONSTRAINT fk_forces_nodes1 FOREIGN KEY (idNode, idDimension)
REFERENCES nodes(idNode, idDimension) ON DELETE CASCADE ON UPDATE CASCADE;

Foreign constraint On Delete Cascade not working

I have a custom table created which has a foreign constraint on the core_website table. However, the on delete cascade isn't working.
I did a search and found this relevant thread, which notes that the data types between the two columns have to be the same. Both data types are smallint(5).
I did notice one minor discrepancy in the column definition, which is that in core_website, Allow Null is not set, and Default is not set to zero, whereas in the account table, Allow Null is set and Default is zero. I didn't think changing these would have any effect, but I went ahead and changed them on the account table to match, but that didn't help.
CREATE TABLE `account` (
`account_id` smallint(11) unsigned NOT NULL AUTO_INCREMENT,
`website_id` smallint(5) unsigned DEFAULT '0',
`code` varchar(64) NOT NULL DEFAULT '',
PRIMARY KEY (`account_id`),
UNIQUE KEY `code` (`code`),
KEY `FK_WEBSITE_ID` (`website_id`),
CONSTRAINT `FK_WEBSITE_ID` FOREIGN KEY (`website_id`) REFERENCES `core_website` (`website_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=44 DEFAULT CHARSET=utf8
try this and let us the result pls.
CREATE TABLE `account` (
`account_id` smallint(11) unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY,
`website_id` smallint(5) unsigned DEFAULT '0',
`code` varchar(64) NOT NULL DEFAULT '',
UNIQUE KEY `code` (`code`),
KEY `FK_WEBSITE_ID` (`website_id`),
CONSTRAINT `FK_WEBSITE_ID` FOREIGN KEY (`website_id`) REFERENCES `core_website` (`website_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=44 DEFAULT CHARSET=utf8
You need add foreign key to core_website table and point it to website_id field in account table. In other words, foreign key should be added to the dependent table and pointed to main table, in this case when you delete row from main table - row from dependent table will be deleted because of FK. In your case you did it "upside down".

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

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;