Foreign key Integrity constraint violation: 1452 - mysql

I've recently started trying to use foreign keys to make database management easier on myself. I'm having a terrible time trying to figure out how they actually work, and most of the time I can get it working between tables without issue. But I'm currently having an issue with 2 of my tables, and I can't figure it out.
I'm getting an error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a child row: a foreign key constraint fails
(REDACTED.rc_logs, CONSTRAINT rc_logs_ibfk_1 FOREIGN
KEY (user_id) REFERENCES rc_teammates (uid) ON DELETE CASCADE ON
UPDATE CASCADE)
[/home5/redacted/public_html/redacted/rc/public/assets/php/connection.php:25]
but my tables seem to be set up properly, and I'm really confused about why it's not working. Here is my table structures:
rc_teammates
CREATE TABLE `rc_teammates` (
`uid` int(11) NOT NULL,
`name` text NOT NULL,
`primary_line` int(11) NOT NULL,
`hireStatus` text NOT NULL,
`created_on` date NOT NULL,
`active` tinyint(1) NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `rc_teammates`
ADD PRIMARY KEY (`uid`), ADD UNIQUE KEY `uid` (`uid`), ADD KEY `primary_line` (`primary_line`), ADD KEY `primary_line_2` (`primary_line`);
ALTER TABLE `rc_teammates`
MODIFY `uid` int(11) NOT NULL AUTO_INCREMENT;
ALTER TABLE `rc_teammates`
ADD CONSTRAINT `rc_teammates_ibfk_1` FOREIGN KEY (`primary_line`) REFERENCES `rc_lines` (`uid`) ON DELETE CASCADE ON UPDATE CASCADE;
rc_logs
CREATE TABLE IF NOT EXISTS `rc_logs` (
`uid` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`line` int(11) NOT NULL,
`date` date NOT NULL,
`type` varchar(15) NOT NULL,
`timein` time NOT NULL,
`timeout` time NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=53 DEFAULT CHARSET=latin1;
ALTER TABLE `rc_logs`
ADD PRIMARY KEY (`uid`), ADD KEY `user_id` (`user_id`), ADD KEY `line` (`line`), ADD KEY `user_id_2` (`user_id`);
ALTER TABLE `rc_logs`
MODIFY `uid` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=53;
ALTER TABLE `rc_logs`
ADD CONSTRAINT `rc_logs_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `rc_teammates` (`uid`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `rc_logs_ibfk_2` FOREIGN KEY (`line`) REFERENCES `rc_lines` (`uid`) ON DELETE CASCADE ON UPDATE CASCADE;
I've tried to look up the error, and I've had this issue before but I do not remember how I solved it. What's worse is, this was working earlier, until I emptied the rc_teammates table to start fresh.
I really cannot figure this out, and would love any pointers. Thanks!

As you said you have "emptied" (TRUNCATE?) the table rc_teammates.
And you try to insert a record in rc_logs, and this record has a user_id that doesn't exists in rc_teammates, thus violation of the following constraint:
ADD CONSTRAINT `rc_logs_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `rc_teammates` (`uid`) ON DELETE CASCADE ON UPDATE CASCADE
Just add a record in rc_teammates, having a uid equal to the user_id of the record you are trying to insert in rc_logs, and retry.
Also, about this :
ALTER TABLE `rc_teammates`
ADD PRIMARY KEY (`uid`), ADD UNIQUE KEY `uid` (`uid`),
ALTER TABLE `rc_teammates`
MODIFY `uid` int(11) NOT NULL AUTO_INCREMENT;
When you set a column as PRIMARY KEY, it is de facto : UNIQUE, NOT NULL and INDEXED. You don't need to specify all this, PRIMARY KEY is enough. This is valid for your other table as well.

Related

How to cascade delete from same MySQL table

Is it possible to cascade delete from same MySQL table? I want to cascade delete in a table that references itself in relations.
Example:
I have a comments table that has comment_id and parent_id, where parent_id is the same id in comment_id.
Parent_id could be either another comment_id or null if it's a root
comment.
I want to be able to select any node in this tree and delete it. In the process, all child nodes and sub-child nodes should be deleted.
I have tried to alter my table using this query
ALTER TABLE `comment`
ADD FOREIGN KEY (`comment_id`)
REFERENCES `comment`(`parent_id`) ON DELETE CASCADE ON UPDATE RESTRICT;
but I end up with an error
Cannot add or update a child row: a foreign key constraint fails
(zendaya001.#sql-6c1_1044ab, CONSTRAINT comment_ibfk_3 FOREIGN
KEY (comment_id) REFERENCES comment (parent_id) ON DELETE
CASCADE ON UPDATE RESTRICT)
For reproduction, this is my comment table:
CREATE TABLE `comment` (
`comment_id` int NOT NULL,
`post_id` int UNSIGNED NOT NULL,
`user_id` int NOT NULL,
`parent_id` int DEFAULT NULL,
`content` text NOT NULL,
`type` varchar(50) DEFAULT NULL,
`count_replies` int NOT NULL DEFAULT '0',
`count_likes` int NOT NULL DEFAULT '0',
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for table `comment`
--
ALTER TABLE `comment`
ADD PRIMARY KEY (`comment_id`),
ADD KEY `user_id` (`user_id`),
ADD KEY `post_id` (`post_id`),
ADD KEY `parent_id` (`parent_id`);
You try to create the foreign key with incorrect direction.
Must be:
ALTER TABLE `comment`
ADD FOREIGN KEY (`parent_id`)
REFERENCES `comment`(`comment_id`) ON DELETE CASCADE ON UPDATE RESTRICT;
https://dbfiddle.uk/iJRlziwL
comment_id must be defined at least UNIQUE (maybe PRIMARY KEY).
I cannot insert a new record into the table even if ON UPDATE RESTRICT is also set to CASCADE – Freesoul
You do something wrongly.
https://dbfiddle.uk/rcUupB2b

Adding multiple foreign key constraints

I am having trouble adding multiple foreign key constraints to this table. I get an error saying
Foreign key constraint is incorrectly formed
Both id's referenced are primary keys in their respective tables. What am I doing wrong?
CREATE TABLE `works_on` (
`eid` int(11) DEFAULT NULL,
`pid` int(11) DEFAULT NULL,
`start_date` date NOT NULL,
PRIMARY KEY (`eid`, `pid`),
CONSTRAINT `works_on_ibfk_1` FOREIGN KEY (`eid`)
REFERENCES `employee` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `works_on_ibfk_2` FOREIGN KEY (`pid`)
REFERENCES `project` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB
You have a paradox here - you cannot have a primary key where any of the elements has a null values AND therefore you cannot on delete SET NULL..
You should also be seeing an error message telling you that the primary key is invalid..

mysql - not able to add foreign key constraint after changing column name

I was changing column name of a column having foreign key constraint, i have done this by
ALTER TABLE `city_details` DROP FOREIGN KEY `tb_city_details_ibfk_1`;
ALTER TABLE `city_details` CHANGE `city_state_id` `city_district_id` int(8) NOT NULL AFTER `city_name`;
now while adding constraint back i'm getting error
1452 - Cannot add or update a child row: a foreign key constraint fails (testdb.#sql-39a8_23, CONSTRAINT city_details_ibfk_1 FOREIGN KEY (city_district_id) REFERENCES district_details (district_id) ON DELETE CASCADE ON UPDATE CASCADE)
i have used this query to add constraint
ALTER TABLE `city_details` ADD CONSTRAINT `city_details_ibfk_1` FOREIGN KEY (`city_district_id`) REFERENCES `district_details`(`district_id`) ON UPDATE CASCADE ON DELETE CASCADE;
SHOW CREATE TABLE city_details
CREATE TABLE `city_details` (
`city_id` int(8) NOT NULL AUTO_INCREMENT,
`city_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`city_district_id` int(8) NOT NULL,
PRIMARY KEY (`city_id`),
KEY `city_state_id` (`city_district_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
Got the issue district_details table was empty but city_details table had few values, after adding values to district_details it is working fine

MySQL primary key column is not unique?

I have the following table in a MySQL database:
CREATE TABLE `datavalues` (
`ValueID` int(11) NOT NULL AUTO_INCREMENT,
`DataValue` double NOT NULL,
`ValueAccuracy` double DEFAULT NULL,
`LocalDateTime` datetime NOT NULL,
`UTCOffset` double NOT NULL,
`DateTimeUTC` datetime NOT NULL,
`SiteID` int(11) NOT NULL,
`VariableID` int(11) NOT NULL,
`OffsetValue` double DEFAULT NULL,
`OffsetTypeID` int(11) DEFAULT NULL,
`CensorCode` varchar(50) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'nc',
`QualifierID` int(11) DEFAULT NULL,
`MethodID` int(11) NOT NULL DEFAULT '0',
`SourceID` int(11) NOT NULL,
`SampleID` int(11) DEFAULT NULL,
`DerivedFromID` int(11) DEFAULT NULL,
`QualityControlLevelID` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`ValueID`),
UNIQUE KEY `DataValues_UNIQUE_DataValues` (`DataValue`,`ValueAccuracy`,`LocalDateTime`,`UTCOffset`,`DateTimeUTC`,`SiteID`,`VariableID`,`OffsetValue`,`OffsetTypeID`,`CensorCode`,`QualifierID`,`MethodID`,`SourceID`,`SampleID`,`DerivedFromID`,`QualityControlLevelID`),
KEY `FK_DataValues_Sites` (`SiteID`),
KEY `FK_DataValues_Sources` (`SourceID`),
KEY `FK_DataValues_QualityControlLevels` (`QualityControlLevelID`),
KEY `FK_DataValues_OffsetTypes` (`OffsetTypeID`),
KEY `FK_DataValues_CensorCodeCV` (`CensorCode`),
KEY `FK_DataValues_Variables` (`VariableID`),
KEY `FK_DataValues_Methods` (`MethodID`),
KEY `FK_DataValues_Qualifiers` (`QualifierID`),
KEY `FK_DataValues_Samples` (`SampleID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
ALTER TABLE `datavalues`
ADD CONSTRAINT `FK_DataValues_Sites` FOREIGN KEY (`SiteID`) REFERENCES `sites` (`SiteID`) ON DELETE NO ACTION ON UPDATE CASCADE,
ADD CONSTRAINT `FK_DataValues_Sources` FOREIGN KEY (`SourceID`) REFERENCES `sources` (`SourceID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_DataValues_QualityControlLevels` FOREIGN KEY (`QualityControlLevelID`) REFERENCES `qualitycontrollevels` (`QualityControlLevelID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_DataValues_OffsetTypes` FOREIGN KEY (`OffsetTypeID`) REFERENCES `offsettypes` (`OffsetTypeID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_DataValues_CensorCodeCV` FOREIGN KEY (`CensorCode`) REFERENCES `censorcodecv` (`Term`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_DataValues_Variables` FOREIGN KEY (`VariableID`) REFERENCES `variables` (`VariableID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_DataValues_Methods` FOREIGN KEY (`MethodID`) REFERENCES `methods` (`MethodID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_DataValues_Qualifiers` FOREIGN KEY (`QualifierID`) REFERENCES `qualifiers` (`QualifierID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_DataValues_Samples` FOREIGN KEY (`SampleID`) REFERENCES `samples` (`SampleID`) ON DELETE NO ACTION ON UPDATE NO ACTION;
When I open my database in PhpMyAdmin 4.0.3 and run a query:
SELECT MAX(DateTimeUTC) from `datavalues`
the query executes but PhpMyAdmin shows a
warning:
This table does not contain a unique column. Grid edit, checkbox,
Edit, Copy and Delete features are not available.
How is it possible? I thought that if I have one column with PRIMARY KEY constraint then the column is UNIQUE. Could this be a bug in PhpMyAdmin? I'm confused.
I found the answer: The warning:
This table does not contain a unique column. Grid edit, checkbox,
Edit, Copy and Delete features are not available.
applies to the current result set and not to the original table.
Álvaro G. Vicario's comment is right.
This appears to be a new thing in PhpMyAdmin 4.0.4 and I find this type of message more confusing than useful.
All you got to do is add a unique column like one called id with a index = PRIMARY like the pic, or if you have one already that is called id that are numbers just make it PRIMARY

How to update foreign key value in mysql database

I have three tables: categories, languages and categories_languages. Categories_languages is many to many table which links together categories and languages. I would like to update a foregin key value in table languages but it throws me error #1451 - Cannot delete or update a parent row: a foreign key constraint fails!
CREATE TABLE IF NOT EXISTS `categories` (
`id` int(11) unsigned NOT NULL auto_increment,
`name` varchar(20) NOT NULL,
`modified` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `languages` (
`id` char(2) NOT NULL,
`name` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `categories_languages` (
`id` int(11) unsigned NOT NULL auto_increment,
`category_id` int(11) unsigned NOT NULL,
`language_id` char(2) NOT NULL,
`translation` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_category_id_language_id` (`category_id`,`language_id`),
KEY `fk_language_id` (`language_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
ALTER TABLE `categories_languages`
ADD CONSTRAINT `categories_languages_ibfk_1` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`) ON DELETE CASCADE,
ADD CONSTRAINT `categories_languages_ibfk_2` FOREIGN KEY (`language_id`) REFERENCES `languages` (`id`) ON DELETE CASCADE;
The error is clear to me, but how can I update a key value in this case? I tried adding ON UPDATA CASCADE:
ALTER TABLE `categories_languages`
ADD CONSTRAINT `categories_languages_ibfk_1` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `categories_languages_ibfk_2` FOREIGN KEY (`language_id`) REFERENCES `languages` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
but that also fails with message: MySQL said: Documentation #1005 - Can't create table './db_dodo/#sql-c2f_80e6f.frm' (errno: 121)
You can temporarily suspend foreign key checking:
SET foreign_key_checks = 0;
UPDATE languages SET id='xyz' WHERE id='abc';
UPDATE categories_languages SET language_id='xyz' WHERE language_id='abc';
SET foreign_key_checks = 1;
EDIT: As for the foreign key problem: is the data stored on a local or a remote file system? errno 121 is EREMOTEIO (Remote I/O error). Perhaps there are permission problems on the target file system or it doesn't support the # character in filenames?
If you are looking for a temp solution you can also change the ON UPDATE action to CASCADE and modify your ids