Cannot add or update a child row: a foreign key constraint fails mysql - 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

Related

I cant add MySQL foreign key constraint

I have three tables user, department, and department_hod
user has a department_id, which is the primary key of department, also departement has hod which is the primary key of user.
But i am getting an error when adding the foreign key constraint of username in department_hod table,
Please help
--
-- Create a user table
--
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`username` varchar(50) NOT NULL,
`password` char(80) NOT NULL,
`emp_id` int(11) NOT NULL,
`designation` varchar(50) NOT NULL,
`department_id` int(11) NOT NULL,
`status` varchar(2) NOT NULL DEFAULT 'A',
`email_id` varchar(50) NOT NULL,
`account_status` varchar(2) NOT NULL DEFAULT 'U',
`validity_date` TIMESTAMP,
`deactivation_date` TIMESTAMP ,
`deactivated_by` varchar(50),
`deactivation_remarks` varchar(1000),
`creation_date` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`updation_date` TIMESTAMP,
`created_by` varchar(50),
`updated_by` varchar(50),
CONSTRAINT `PK_USER_ID` PRIMARY KEY (`id`,`username`),
KEY `FK_DEPARTMENT_IDX_01` (`department_id`),
CONSTRAINT `FK_DEPARTMENT_ID_01` FOREIGN KEY (`department_id`)
REFERENCES `department` (`id`)
ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
--
-- Create a department table
--
CREATE TABLE `department` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`status` varchar(2) NOT NULL DEFAULT 'A',
`creation_date` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`updation_date` TIMESTAMP,
`created_by` varchar(50),
`updated_by` varchar(50),
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
--
-- Add department_hod table
--
CREATE TABLE `department_hod` (
`department_id` int(11) NOT NULL,
`username` varchar(50) NOT NULL,
PRIMARY KEY (`username`,`department_id`),
KEY `FK_DEPARTMENT_idx_02` (`department_id`),
CONSTRAINT `FK_DEPARTMENT_id_02` FOREIGN KEY (`department_id`)
REFERENCES `department` (`id`)
ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `FK_USER_01` FOREIGN KEY (`username`)
REFERENCES `user` (`username`)
ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
SET FOREIGN_KEY_CHECKS = 1;
error is here
CONSTRAINT `FK_USER_01` FOREIGN KEY (`username`)
REFERENCES `user` (`username`)
ON DELETE NO ACTION ON UPDATE NO ACTION
Error is
Error Code: 1215. Cannot add foreign key constraint
Always provide complete error message. In a half of choices you may find the solution in it.
For your code the error message is
Failed to add the foreign key constraint. Missing index for constraint 'FK_USER_01' in the referenced table 'user'
So the problem can be fixed by absent index creation:
CREATE INDEX idx_user_username ON user (username);
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=1f0fd24a8eb9cb5692b9d35dd1903045
can you please tell me that is it necessary to use index here? as it is only used for speeding up, do i have to use it beacuse of two primary keys in my user table? – shah-123
MySQL 8.0 Reference Manual / ... / FOREIGN KEY Constraints / Conditions and Restrictions
MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist. This index might be silently dropped later if you create another index that can be used to enforce the foreign key constraint. index_name, if given, is used as described previously.

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.

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.

Foreign Key not working: Error code 1005, SQL state HY000: Can't create table

I have two tables I have created and I'm adding the foreign key constraint after the fact.
The two tables are defined as such:
CREATE TABLE `user` (
`user_id` int(11) NOT NULL auto_increment,
`user_ad_id` varchar(500) default NULL,
`user_name` varchar(100) NOT NULL,
`login_id` varchar(100) default NULL,
`email` varchar(256) NOT NULL,
`personal_config` int(10) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
and
CREATE TABLE IF NOT EXISTS personal_config (
config_id INT(10) NOT NULL AUTO_INCREMENT,
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
configuration TEXT(25600) NOT NULL,
PRIMARY KEY (config_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE personal_config ADD CONSTRAINT personal_config_fk_user FOREIGN KEY
(config_id) REFERENCES user(personal_config);
And I keep getting the same error but can't figure it out. I've searched all the related threads to this.
Your FK config_id can't be an autoincrement field, that doesn't make much sense right? That field reflects a value in the foreign table, it cannot be set arbitrarily in the local table.
I think this is what you want:
ALTER TABLE user ADD CONSTRAINT personal_config_fk_user FOREIGN KEY (personal_config) REFERENCES personal_config(config_id);
Your ALTER TABLE statement is backward. Since personal_config.config_id is an auto_increment primary key, the foreign key should be defined in the users table against personal_config, not in personal_config against the users table.
ALTER TABLE users ADD CONSTRAINT user_fk_personal_config
FOREIGN KEY (personal_config)
REFERENCES personal_config(config_id);
if you set your user table field personal_config is primary key then it is possible to execute
CREATE TABLE IF NOT EXISTS personal_config (
config_id INT(10) NOT NULL AUTO_INCREMENT,
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
configuration TEXT(25600) NOT NULL,
PRIMARY KEY (config_id), FOREIGN KEY
(config_id) REFERENCES user(personal_config)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;