Error #1452 when altering mySQL table to add foreign key - mysql

Trying to help an intern with her project. She wants to add foreign keys to an existing table but this query:
ALTER TABLE `document`
ADD CONSTRAINT `document_ibfk_1` FOREIGN KEY (`cle_author`)
REFERENCES `author` (`id_author`)
ON DELETE CASCADE
ON UPDATE CASCADE;
gives this error:
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`wrc_mysql`.<result 2 when explaining filename '#sql-30e4_7000d'>, CONSTRAINT `document_ibfk_1` FOREIGN KEY (`cle_author`) REFERENCES `author` (`id_author`) ON DELETE CASCADE ON UPDATE CASCADE)
Schema are like so
CREATE TABLE `document` (
`id_document` int(11) NOT NULL AUTO_INCREMENT,
`abstract` text,
`number_of_pages` int(10) DEFAULT NULL,
`original_surrey_citation` varchar(255) DEFAULT NULL,
`updated_citation` varchar(255) DEFAULT NULL,
`library_of_congress` varchar(10) DEFAULT NULL,
`cross_citation` varchar(50) DEFAULT NULL,
`doc_type` varchar(255) DEFAULT NULL,
`questions` varchar(255) DEFAULT NULL,
`keywords` varchar(255) DEFAULT NULL,
`cle_author` int(10) NOT NULL,
PRIMARY KEY (`id_document`),
KEY `cle_author` (`cle_author`)
) ENGINE=InnoDB AUTO_INCREMENT=22591 DEFAULT CHARSET=utf8
CREATE TABLE `author` (
`id_author` int(10) NOT NULL AUTO_INCREMENT,
`author_name` varchar(255) DEFAULT NULL,
`sender_office` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id_author`),
KEY `author_name` (`author_name`,`sender_office`)
) ENGINE=InnoDB AUTO_INCREMENT=22591 DEFAULT CHARSET=utf8
Anyone know what is going wrong?

You probably have inconsistent data between your two tables. This error means that you have a cle_author value in your document table that doesn't have a corresponding entry in the author table. Since the cle_author value is going to be set up as a foreign key, each value for that field must have a corresponding entry in the author table's id_author field.

Per this page: Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails
checked intern's data with
SELECT cle_author FROM document doc
LEFT JOIN author a ON doc.cle_author=a.id_author
WHERE a.id_author IS NULL;
And found ALL of her cle_author data is bogus and does not hold valid references to id_author values.

Related

MySQL error: Missing index for constraint

I am creating 2 tables in my database:
DROP TABLE IF EXISTS `med_pharmacy`;
CREATE TABLE IF NOT EXISTS `med_pharmacy` (
`med_pharmacy_id` int(11) NOT NULL AUTO_INCREMENT,
`med_id` int(11) NOT NULL,
`med_barcode` varchar(45) DEFAULT NULL,
`med_received` date DEFAULT NULL,
`med_expiry` date DEFAULT NULL,
`med_tablet` int(11) DEFAULT NULL,
`med_pill` int(11) DEFAULT NULL,
`clinic_id` varchar(45) DEFAULT NULL,
PRIMARY KEY (`med_pharmacy_id`),
KEY `fk_med_pharmacy_medication1_idx` (`med_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1261 DEFAULT CHARSET=utf8mb4;
AND:
DROP TABLE IF EXISTS `medication`;
CREATE TABLE `medication` (
`med_id` int(11) NOT NULL,
`med_name` varchar(75) NOT NULL,
`med_date_added` date DEFAULT NULL,
`clinic_id` varchar(45) DEFAULT NULL,
`med_type` varchar(15) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
And when I run the queries in wamp I got this error:
SQL query:
ALTER TABLE `med_pharmacy`
ADD CONSTRAINT `fk_med_pharmacy_medication1`
FOREIGN KEY (`med_id`)
REFERENCES
`medication` (`med_id`) ON DELETE CASCADE ON UPDATE CASCADE MySQL
said: Documentation
#1822 - Failed to add the foreign key constaint. Missing index for constraint 'fk_med_pharmacy_medication1' in the referenced table
'medication'
The tables already exists but I changed one field.
The column referenced in a foreign key must be indexed. You need to add an index on medication.med_id. In fact, this should probably be the primary key of the table.
ALTER TABLE medication ADD PRIMARY KEY (med_id);
if you are giving
ADD CONSTRAINT `fk_med_pharmacy_medication1`
FOREIGN KEY (`med_id`)
A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.
so med_id should have primary key in medication or reference the columns of a UNIQUE constraint

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

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