mysql - foreign key cascade update - mysql

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;

Related

MySQL cascade hard delete child row on soft delete of parent row without using a trigger: is this possible?

I'm using MySQL version 5.6.47-87.0
I have a parent table named parentTable and a child table named childTable, here's the scripts to create those tables:
CREATE TABLE `parentTable` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`customerId` int(10) unsigned NOT NULL,
`modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`deleted` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=251046 DEFAULT CHARSET=utf8;
CREATE TABLE `childTable` (
`parentId` int(10) unsigned NOT NULL,
`name` varchar(255) NOT NULL,
`description` text
PRIMARY KEY (`parentId`),
CONSTRAINT `childtable_parentid_foreign` FOREIGN KEY (`parentId`) REFERENCES `parentTable` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
As is the child record in childTable is hard deleted when the corresponding record in the parentTable is hard deleted.
Without using a trigger, is it possible to set this up so the record in childTable is hard deleted when the corresponding record in parentTable is soft deleted (IE: when the parentTable.deleted column is updated with a value so is it no longer NULL)?

MySQL Error 1452 when inserting data

I keep getting errors when importing my old SQL file and fix them all,but I'm stuck and can't understand what this means.
ALTER TABLE property ADD CONSTRAINT property_ibfk_1 FOREIGN KEY
(intid) REFERENCES interiors (id) ON DELETE CASCADE ON UPDATE
CASCADE, ADD CONSTRAINT property_ibfk_2 FOREIGN KEY (owner)
REFERENCES accounts (id) ON DELETE SET NULL ON UPDATE CASCADE
MySQL said: Documentation
1452 - Cannot add or update a child row: a foreign key constraint fails (ionicnew.#sql-252c_e1, CONSTRAINT property_ibfk_2 FOREIGN
KEY (owner) REFERENCES accounts (id) ON DELETE SET NULL ON
UPDATE CASCADE)
Full code of property table:
CREATE TABLE `property` (
`id` int(11) NOT NULL,
`x` float NOT NULL,
`y` float NOT NULL,
`z` float NOT NULL,
`a` float NOT NULL,
`type` bit(32) NOT NULL,
`intid` int(11) NOT NULL,
`name` varchar(128) NOT NULL,
`price` int(11) NOT NULL,
`mapicon` tinyint(3) UNSIGNED NOT NULL,
`status` tinyint(3) UNSIGNED NOT NULL,
`point` int(10) UNSIGNED NOT NULL,
`saleprice` int(11) NOT NULL DEFAULT '0',
`owner` int(11) DEFAULT NULL,
`money` int(11) NOT NULL DEFAULT '0',
`level` tinyint(3) UNSIGNED NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `property`
ADD PRIMARY KEY (`id`),
ADD KEY `intid` (`intid`),
ADD KEY `owner` (`owner`);
ALTER TABLE `property`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=86;
ALTER TABLE `property`
ADD CONSTRAINT `property_ibfk_1` FOREIGN KEY (`intid`) REFERENCES `interiors` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `property_ibfk_2` FOREIGN KEY (`owner`) REFERENCES `accounts` (`id`) ON DELETE SET NULL ON UPDATE CASCADE;
I can upload the full SQL file if needed.
Foreign key relationships involve a parent table that holds the
central data values, and a child table with identical values pointing
back to its parent. The FOREIGN KEY clause is specified in the child
table.
It will reject any INSERT or UPDATE operation that attempts to create
a foreign key value in a child table if there is no a matching
candidate key value in the parent table.
To know more Go to this link
So your error Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails essentially means that, you are trying to add a row to your property table for which no matching row (intid) is present in interiors table.
You must first insert the row to your interiors table.

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 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

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;