composite primary key as foreign key deleting one set delets all - mysql

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.

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

Foreign Key Constraints Errors

I keep getting a ERROR1215 when I create my table. I have narrowed the problem down to two attributes "score" and "criteriaNum". I cannot figure out why its causing problems though.
CREATE TABLE IF NOT EXISTS `sys`.`rubric` (
`programName` VARCHAR(100) NOT NULL,
`criteriaNum` INT UNSIGNED NOT NULL,
`score` INT UNSIGNED NOT NULL,
`criteria` TINYTEXT NOT NULL,
`description` TINYTEXT NOT NULL,
PRIMARY KEY (`programName`, `criteriaNum`,`score`),
CONSTRAINT `rubric_programName`
FOREIGN KEY (`programName`)
REFERENCES `sys`.`degree_program` (`programName`)
ON DELETE CASCADE
ON UPDATE CASCADE)
COMMENT 'Each entry in the rubric table corresponds to a criteria,score pair.';
CREATE TABLE IF NOT EXISTS`sys`.`evaluator_scores` (
`evaluatorName` VARCHAR(100) NOT NULL,
`aid` INT NOT NULL,
`programName` VARCHAR(100) NOT NULL,
`criteriaNum` INT UNSIGNED NOT NULL,
`score` INT UNSIGNED NOT NULL,
PRIMARY KEY (`aid`, `evaluatorName`, `programName`, `criteriaNum`, `score`),
CONSTRAINT `score_aid`
FOREIGN KEY (`aid`)
REFERENCES `sys`.`application` (`aid`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `score_evalName`
FOREIGN KEY (`evaluatorName`)
REFERENCES `sys`.`evaluations` (`evaluatorName`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `score_programName`
FOREIGN KEY (`programName`)
REFERENCES `sys`.`rubric` (`programName`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `score_criteriaNum`
FOREIGN KEY (`criteriaNum`)
REFERENCES `sys`.`rubric` (`criteriaNum`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `score_score`
FOREIGN KEY (`score`)
REFERENCES `sys`.`rubric` (`score`)
ON DELETE CASCADE
ON UPDATE CASCADE);
If I remove the score and criteriaNum constraints, it builds evaluator_scores. Otherwise though I get errors. Can anyone find the problem?
The concept of foreign keys is that the parent table must have a corresponding record in order to include that key in the child. In your parent table, the primary key is (programName, criteriaNum, score). Yet in your child table, you are trying to create three foreign key constraints to the rubric table, one for each individual column.
If you combine those three constraints into one and match the primary key columns, it ought to work.

Cannot add foreign key constraint, 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

mysql foreign key references same table field

I have this table
CREATE TABLE `product_category` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(255) NOT NULL,
`category_id` int(11) NOT NULL default '0',
PRIMARY KEY (`id`),
KEY `category_id` (`category_id`),
CONSTRAINT `category_id` FOREIGN KEY (`category_id`) REFERENCES `product_category` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB
What I'm trying to get is to delete on cascade every record which category_id fields equals to id field, but I cant insert any record, it gives me an error
cannot add or update a child row: a foreign key constraint fails('database/product_category', CONSTRAINT 'category_id FOREIGN KEY('category_id') REFERENCES product_category('id') ON DELETE CASCADE ON UPDATE CASCADE
Your foreigh key value must point to existing product_category (id), but there are no allowable rows in table. So make
category_id int(11) NULL,
instead your definition and insert first row like
INSERT INTO product_category SET name='test1';

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