I am trying to add to my database table, but seem to get an error. I get a 1452 Error. Here is what I think is the problem: I think my parent_fk is referring to an id what does not yet exist. At least that is what I understand of the following error:
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (assetgallery.ag_asset, CONSTRAINT fk_ag_asset_2 FOREIGN KEY (parent_fk) REFERENCES ag_asset (id) ON DELETE CASCADE ON UPDATE CASCADE)
Say I have a tuple in my database with the id 2. The first tuple:
'2', '8', NULL, NULL, '2', '2015-09-24 09:42:31', 'sabernLogo_0.png', NULL, NULL, NULL, '180', '80', NULL, '1', NULL, NULL, '3', '1'
I am trying to add another with an INSERT statement. I am Inserting without an id, so it looks like this :
Insert into ag_asset
(album_fk, parent_fk, head_fk, status_fk, modified, filename, title, `desc`, `text`, width, height, owner_fk, locked, remarks, group_fk, user_fk, type_fk)
VALUES(6, 0, null, 1, '2015-10-15 15:47:13.0', 'index.png', null, null, null, 215, 234, null, null, null, null, 3, 1);
From what I understand because my id is Autoincrement'ed, not filling this in would result in a freshly made id, being 2.
Here is the create statement
CREATE TABLE `ag_asset` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`album_fk` int(10) DEFAULT NULL,
`parent_fk` int(10) DEFAULT NULL,
`head_fk` int(10) DEFAULT NULL,
`status_fk` int(10) DEFAULT '1',
`modified` datetime NOT NULL,
`filename` varchar(255) DEFAULT NULL,
`title` varchar(255) DEFAULT NULL,
`desc` text,
`text` longtext,
`width` int(10) DEFAULT NULL,
`height` int(10) DEFAULT NULL,
`owner_fk` int(10) DEFAULT NULL,
`locked` int(10) DEFAULT NULL,
`remarks` text,
`group_fk` int(10) DEFAULT NULL,
`user_fk` int(10) DEFAULT NULL,
`type_fk` int(10) DEFAULT '1',
PRIMARY KEY (`id`),
KEY `in_filename` (`filename`(12)),
KEY `in_title` (`title`(12)),
KEY `fk_ag_asset_1` (`album_fk`),
KEY `fk_ag_asset_2` (`parent_fk`),
KEY `fk_ag_asset_3` (`head_fk`),
KEY `fk_ag_asset_4` (`status_fk`),
KEY `fk_ag_asset_5` (`owner_fk`),
KEY `fk_ag_asset_6` (`type_fk`),
CONSTRAINT `fk_ag_asset_1` FOREIGN KEY (`album_fk`) REFERENCES `ag_album` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_ag_asset_2` FOREIGN KEY (`parent_fk`) REFERENCES `ag_asset` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_ag_asset_3` FOREIGN KEY (`head_fk`) REFERENCES `ag_asset` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_ag_asset_4` FOREIGN KEY (`status_fk`) REFERENCES `ag_status` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_ag_asset_5` FOREIGN KEY (`owner_fk`) REFERENCES `ag_owner` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_ag_asset_6` FOREIGN KEY (`type_fk`) REFERENCES `ag_type` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8;
Do I understand the error correctly or am I even looking in the wrong direction?
In foreign key concept whatever value you are trying to insert/update in child table, must exist in its parent/referenced table.
Here you are trying to insert values like 0, NULL etc in columns for those you have created referenced and your master table does not keep these values.
Solution1:
Either first add these values in master table then you can insert in child table.
Solution2:
If you want to add such data in child table forcefully as per your requirement which is not suggested then you can do as-
set foreign_key_checks=0;
Insert statement here...
set foreign_key_checks=1;
Related
I'm quite new to SQL, and I'm trying to upload data to my tables. For this I have special tables where I upload the data from a CSV file, and then, from this table, I am trying to copy the data to the final table.
But now I have a problem with an intermediate table where I have uploaded my data. The table is:
CREATE TABLE `_work_has_person` (
`work_id` int(11) NOT NULL,
`person_id` int(11) NOT NULL,
`primary_contribution_id` int(11) DEFAULT NULL,
PRIMARY KEY (`work_id`,`person_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I want to copy the data in
CREATE TABLE `work_has_person` (
`work_id` int(11) NOT NULL,
`person_id` int(11) NOT NULL,
`primary_contribution_id` int(11) NOT NULL,
PRIMARY KEY (`work_id`,`person_id`),
KEY `fk_work_has_person_person1_idx` (`person_id`),
KEY `fk_work_has_person_work1_idx` (`work_id`),
KEY `fk_work_has_person_primary_contribution1_idx` (`primary_contribution_id`),
CONSTRAINT `fk_work_has_person_person1` FOREIGN KEY (`person_id`) REFERENCES `person` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_work_has_person_primary_contribution1` FOREIGN KEY (`primary_contribution_id`) REFERENCES `primary_contribution` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_work_has_person_work1` FOREIGN KEY (`work_id`) REFERENCES `work` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Which is an intermediate table between:
CREATE TABLE `work` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title_work` varchar(250) DEFAULT NULL,
`subtitle_work` varchar(250) DEFAULT NULL,
`date_work` varchar(45) DEFAULT NULL,
`unix_date_work` varchar(100) DEFAULT NULL,
`sinopsis` text,
`ref_bne` varchar(100) DEFAULT NULL,
`ref_alt` longtext,
`language_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_work_language1_idx` (`language_id`),
KEY `title_work` (`title_work`),
CONSTRAINT `fk_work_language1` FOREIGN KEY (`language_id`) REFERENCES `language` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=24610 DEFAULT CHARSET=utf8;
and
CREATE TABLE `person` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`img_person` varchar(250) DEFAULT NULL,
`born_date` varchar(45) DEFAULT NULL,
`unix_born_date` varchar(100) DEFAULT NULL,
`city_born_date` varchar(100) DEFAULT NULL,
`country_born_date` varchar(100) DEFAULT NULL,
`death_date` varchar(45) DEFAULT NULL,
`unix_death_date` varchar(100) DEFAULT NULL,
`city_death_date` varchar(100) DEFAULT NULL,
`country_death_date` varchar(45) DEFAULT NULL,
`biography` longtext,
`ref_bne` varchar(100) DEFAULT NULL,
`ref_alt` longtext,
PRIMARY KEY (`id`),
UNIQUE KEY `name_UNIQUE` (`name`),
KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=9159 DEFAULT CHARSET=utf8;
But everytime I try to run
INSERT INTO work_has_person (work_id, person_id, primary_contribution_id)
SELECT work_id, person_id, primary_contribution_id
FROM _work_has_person;
It says
Cannot add or update a child row: a foreign key constraint fails (`cdu93hfg93r`.
`work_has_person`, CONSTRAINT `fk_work_has_person_person1` FOREIGN KEY (`person_id`)
REFERENCES `person` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
I am pretty sure that the tables has the neccesary data, but, ¿is there a way to know which data fails? I have seen Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails: but don't understand exactly how to use it here.
A.
It is relatively easy to find out what data is causing the conflict: get all person_ids from _work_has_person that are not in the persons table. You can achieve this via an outer join and filtering for person.id is null in the where clause.
select * from `_work_has_person` whp
left join person p on whp.person_id=p.id
where p.id is null
You can actually remove such data from the results being inserted by including the reverse criterion into the select part of your insert query (an inner join):
INSERT INTO work_has_person (work_id, person_id, primary_contribution_id)
SELECT whp.work_id, whp.person_id, whp.primary_contribution_id
FROM _work_has_person whp
INNER join person p on whp.person_id=p.id
I have a workflow in my application where an admin for an organization can add a user to their organization. Once a form submission, I first insert a new record into my user table with the users email and the organization id associated with the admin. After that user is created, a member record which connects the user to the organization is created with the users email and the users organization id and user_id. The issue I am running into is with creating a record on the member table with the recently created users user_id. While I have no issue storing the organization_id present, for some reason passing the user_id throws an error related to the foreign key:
Cannot add or update a child row: a foreign key constraint fails (`work`.`member`, CONSTRAINT `member_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `organization` (`organization_id`) ON DELETE CASCADE ON UPDATE CASCADE)]
Why can't I pass the user_id on record creation. Is it because the column is associated to a foreign key?
Here are the inserts:
User insert (No error):
INSERT INTO `user` (`user_id`,`email`,`organization_id`,`updatedAt`,`createdAt`) VALUES (DEFAULT,'test+email#gmail.com','1','2016-06-07 11:51:54','2016-06-07 11:51:54');
Member insert (Error with user_id):
INSERT INTO `member` (`member_id`,`member_email`,`organization_id`,`user_id`,`updatedAt`,`createdAt`) VALUES (DEFAULT,'test+email#gmail.com','1',8,'2016-06-07 11:51:54','2016-06-07 11:51:54');
User Table:
`user` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(255) DEFAULT NULL,
`last_name` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`organization_id` int(11) DEFAULT NULL,
`authentication_token` varchar(255) DEFAULT NULL,
`reset_password_token` varchar(255) DEFAULT NULL,
`reset_password_expires` datetime DEFAULT NULL,
`createdAt` datetime NOT NULL,
`updatedAt` datetime NOT NULL,
PRIMARY KEY (`user_id`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
Organization table:
`organization` (
`organization_id` int(11) NOT NULL AUTO_INCREMENT,
`organization_name` varchar(255) DEFAULT NULL,
`admin` varchar(255) DEFAULT NULL,
`createdAt` datetime NOT NULL,
`updatedAt` datetime NOT NULL,
PRIMARY KEY (`organization_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
Member table:
`member` (
`member_id` int(11) NOT NULL AUTO_INCREMENT,
`member_email` varchar(255) DEFAULT NULL,
`organization_id` int(11) DEFAULT NULL,
`user_id` int(11) DEFAULT NULL,
`createdAt` datetime NOT NULL,
`updatedAt` datetime NOT NULL,
PRIMARY KEY (`member_id`),
UNIQUE KEY `member_email` (`member_email`),
UNIQUE KEY `member_user_id_organizationId_unique` (`organization_id`,`user_id`),
KEY `user_id` (`user_id`),
CONSTRAINT `member_ibfk_1` FOREIGN KEY (`organization_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `member_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `organization` (`organization_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
Seem to me that you got your constraints mixed up.
I created the tables using your sql and reverse engineered with MySQLWorkbench to get an EER containing your tables.
On first sight you can see that organization_id in table organization is linked with user_id in members table.
If you change your constraints to the following, it will work:
CONSTRAINT `member_ibfk_1` FOREIGN KEY (`organization_id`) REFERENCES `organization` (`organization_id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `member_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE
Try to change the CONSTRAINT member_ibfk_1 to this:
CONSTRAINT `member_ibfk_1` FOREIGN KEY (`organization_id`) REFERENCES user(`user_id`) ON DELETE CASCADE ON UPDATE CASCADE,
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.
I can't seem to figure out why my foreign key constraints aren't working. Here's my table schema:
CREATE TABLE `templates_textboxes` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`template_id` int(10) unsigned DEFAULT NULL,
`textbox_id` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `templates_textboxes_to_templates_idx` (`template_id`),
KEY `templates_textboxes_to_textboxes_idx` (`textbox_id`),
CONSTRAINT `templates_textboxes_to_templates` FOREIGN KEY (`template_id`) REFERENCES `templates` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1$$
CREATE TABLE `textboxes` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`content` text NOT NULL,
`columns` tinyint(1) unsigned NOT NULL DEFAULT '1',
`width` int(5) unsigned NOT NULL DEFAULT '0',
`height` int(5) unsigned NOT NULL DEFAULT '0',
`x` int(5) unsigned NOT NULL DEFAULT '0',
`y` int(5) unsigned NOT NULL DEFAULT '0',
`z` int(5) unsigned NOT NULL DEFAULT '500',
PRIMARY KEY (`id`),
CONSTRAINT `textboxes_to_templates_textboxes` FOREIGN KEY (`id`) REFERENCES `templates_textboxes` (`textbox_id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8$$
When I create a textbox in PHP, first I insert into textboxes to get the ID then insert a row in the match table templates_textboxes with the template id and new textbox id. I've read every post I can find on here about foreign keys allowing nulls and all it says to do is to set the foreign key column (templates_textboxes.textbox_id) to allow nulls. I tried that and when I try to insert into textboxes I get the following error:
Error Number: 1452
Cannot add or update a child row: a foreign key constraint fails (`pitchperfect`.`textboxes`, CONSTRAINT `textboxes_to_templates_textboxes` FOREIGN KEY (`id`) REFERENCES `templates_textboxes` (`textbox_id`) ON DELETE CASCADE ON UPDATE NO ACTION)INSERT INTO `textboxes` (`content`, `columns`, `width`, `height`, `x`, `y`, `z`) VALUES ('', '1', '400', '300', '133', '93', '500')
What I'm trying to accomplish is have cascade deletes chain from themes, to templates and their assets (templates_textboxes -> textboxes).
Thanks!
Since textboxes.id is not yet defined and is AUTO_INCREMENT, that value must first exist in templates_textboxes.textbox_id. This is why the constraint is failing.
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;