Cannot add foreign key constraint, mysql - mysql

I have three tables: advocate, client and event. In event table, I have two fields that are referencing two fields from advocate table and one field referencing client, and when I try to add foreign key I get this cannot add foreign key constraint error.
create table advocate(
ida int(11) not null,
idk int(11) not null,
#...
primary key(ida, idk)
)engine = InnoDB default charset=utf8;
create table client(
jmb varchar(13) not null primary key
#...
)engine=InnoDB default charset=utf8;
create table event(
ida int(11) not null,
idk int(11) not null,
jmb varchar(13) not null,
#...
primary key(ida,idk,jmb),
foreign key(ida, idk)
references advocate(ida, idk)
on update cascade
on delete restrict,
foreign key(jmb)
references client.jmb
on update cascade
on delete restrict
)engine=InnoDB default charset=utf8;

Can you try changing:
foreign key(jmb)
references client.jmb
on update cascade
on delete restrict
to
foreign key(jmb)
references client (jmb)
on update cascade
on delete restrict

Related

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

composite primary key as foreign key deleting one set delets all

I have two tables one of them has composite primary key and the other has foreign keys to it. They both are set to cascade on delete. The problem is when I delete lets say a composite key set "name: John date: 02.02.2018" from the main table all the John rows are deleted from the table with the foreign keys, but there can be a set "name: John date: 04.04.2018" and also all rows where date is 02.02.2018 are also deleted how can I make it delete rows where only the set of foreign key is matched?
Update:
CREATE TABLE messages (
session_date date NOT NULL,
chat int(11) NOT NULL,
message longtext NOT NULL,
date time NOT NULL,
receiver int(11) NOT NULL,
PRIMARY KEY (date,receiver),
KEY FK_messages_sessions (session_date,chat),
KEY FK_messages_sessions_2 (chat,session_date),
CONSTRAINT FK_messages_sessions
FOREIGN KEY (session_date)
REFERENCES sessions (session_date)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FK_messages_sessions_2
FOREIGN KEY (chat)
REFERENCES sessions (chat)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1
You have defined two foreign keys instead of a composite foreign key.
Try:
CREATE TABLE `messages` (
`session_date` date NOT NULL,
`chat` int(11) NOT NULL,
`message` longtext NOT NULL,
`date` time NOT NULL,
`receiver` int(11) NOT NULL,
PRIMARY KEY (`date`,`receiver`),
KEY `FK_messages_sessions` (`session_date`,`chat`),
CONSTRAINT `FK_messages_sessions`
FOREIGN KEY (`session_date`, `chat`)
REFERENCES `sessions` (`session_date`, `chat`)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1
(session_date,chat) could also be (chat,session_date) depending on the order of these columns in the primary key defined in the referenced table.

Foreign key Integrity constraint violation: 1452

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.

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