Proper use of ON CASCADE UPDATE? - mysql

While trying to run the following query:
UPDATE Flight
SET FLNO = '1001'
WHERE FLNO = '1000';
I receive the following error:
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`user/FlightLegInstance`, CONSTRAINT `FlightLegInstance_ibfk_1` FOREIGN KEY (`FLNO`) REFERENCES `FlightLeg` (`FLNO`) ON UPDATE CASCADE)
The following are my creation queries:
Flight:
CREATE TABLE Flight (
FLNO INTEGER NOT NULL,
Meal varchar(50) NOT NULL,
Smoking char(1) NOT NULL,
PRIMARY KEY (FLNO)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
FlightLeg:
CREATE TABLE FlightLeg (
FLNO INTEGER NOT NULL,
Seq char(25) NOT NULL,
FromA char(3) NOT NULL,
ToA char(3) NOT NULL,
DeptTime DATETIME NOT NULL,
ArrTime DATETIME NOT NULL,
Plane INTEGER NOT NULL,
PRIMARY KEY (FLNO, Seq),
FOREIGN KEY (FLNO) REFERENCES Flight(FLNO) ON UPDATE CASCADE,
FOREIGN KEY (FromA) REFERENCES Airport(Code),
FOREIGN KEY (ToA) REFERENCES Airport(Code)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
FlightLegInstance:
CREATE TABLE FlightLegInstance (
Seq char(25) NOT NULL,
FLNO INTEGER NOT NULL,
FDate DATE NOT NULL,
ActDept DATETIME NOT NULL,
ActArr DATETIME NOT NULL,
Pilot INTEGER NOT NULL,
PRIMARY KEY (Seq, FLNO, FDate),
FOREIGN KEY (FLNO) REFERENCES FlightLeg(FLNO) ON UPDATE CASCADE,
FOREIGN KEY (FLNO, FDate) REFERENCES FlightInstance(FLNO, FDate) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I would assume that the error is in one of the two FK definitions of FlightLegInstance, but I'm not sure. Can anyone help me with this?
Thanks.

this is not working just because you have defind [flno] column in second table as foriegn key
the solution of this problem is you have to update it at both places
thanks

Related

Error Code: 1822. Failed to add the foreign key constraint

CREATE TABLE `branch` (
`BranchID` INT NOT NULL,
`BranchSuburb` varchar(255) NOT NULL,
`BranchState` char(3) NOT NULL,
PRIMARY KEY (`BranchID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `member` (
`MemberID` INT NOT NULL,
`MemberStatus` char(9) DEFAULT 'REGULAR',
`MemberName` varchar(255) NOT NULL,
`MemberAddress` varchar(255) NOT NULL,
`MemberSuburb` varchar(25) NOT NULL,
`MemberState` char(3) NOT NULL,
`MemberExpDate` DATE,
`MemberPhone` varchar(10),
PRIMARY KEY (`MemberID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `publisher` (
`PublisherID` INT NOT NULL,
`PublisherName` varchar(255) NOT NULL,
`PublisherAddress` varchar(255) DEFAULT NULL,
PRIMARY KEY (`PublisherID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `book` (
`BookID` INT NOT NULL,
`BookTitle` varchar(255) NOT NULL,
`PublisherID` INT NOT NULL,
`PublishedYear` INT4,
`Price` Numeric(5,2) NOT NULL,
PRIMARY KEY (`BookID`),
KEY `PublisherID` (`PublisherID`),
CONSTRAINT `publisher_fk_1` FOREIGN KEY (`PublisherID`) REFERENCES `publisher` (`PublisherID`) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `author` (
`AuthorID` INT NOT NULL,
`AuthorName` varchar(255) NOT NULL,
`AuthorAddress` varchar(255) NOT NULL,
PRIMARY KEY (`AuthorID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `authoredby` (
`BookID` INT NOT NULL,
`AuthorID` INT NOT NULL,
PRIMARY KEY (`BookID`,`AuthorID`),
KEY `bookID` (`BookID`),
KEY `AuthorID` (`AuthorID`),
CONSTRAINT `book_fk_1` FOREIGN KEY (`BookID`) REFERENCES `book` (`bookID`) ON DELETE RESTRICT,
CONSTRAINT `author_fk_1` FOREIGN KEY (`AuthorID`) REFERENCES `author` (`AuthorID`) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `holding` (
`BranchID` INT NOT NULL,
`BookID` INT NOT NULL,
`InStock` INT DEFAULT 1,
`OnLoan` INT DEFAULT 0,
PRIMARY KEY (`BranchID`,`BookID`),
KEY `bookID` (`BookID`),
KEY `BranchID` (`BranchID`),
CONSTRAINT `holding_cc_1` CHECK(`InStock`>=`OnLoan`),
CONSTRAINT `book_fk_2` FOREIGN KEY (`BookID`) REFERENCES `book` (`bookID`) ON DELETE RESTRICT,
CONSTRAINT `branch_fk_1` FOREIGN KEY (`BranchID`) REFERENCES `branch` (`BranchID`) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `borrowedby` (
`BookIssueID` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`BranchID` INT NOT NULL,
`BookID` INT NOT NULL,
`MemberID` INT NOT NULL,
`DateBorrowed` DATE,
`DateReturned` DATE DEFAULT NULL,
`ReturnDueDate` DATE,
PRIMARY KEY (`BookIssueID`),
KEY `bookID` (`BookID`),
KEY `BranchID` (`BranchID`),
KEY `MemberID` (`MemberID`),
CONSTRAINT `borrowedby_cc_1` CHECK(`DateBorrowed`<`ReturnDueDate`),
CONSTRAINT `holding_fk_1` FOREIGN KEY (`BookID`,`BranchID`) REFERENCES `holding` (`BookID`,`BranchID`) ON DELETE RESTRICT,
CONSTRAINT `member_fk_1` FOREIGN KEY (`MemberID`) REFERENCES `member` (`MemberID`) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Im getting the following error when i try to execute the last create query for the borrowedby table.
Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'holding_fk_1' in the referenced table 'holding'
have you tried to split the double foreign key? like this:
CONSTRAINT `holding_fk_1` FOREIGN KEY (`BookID`) REFERENCES `holding` (`BookID`) ON DELETE RESTRICT,
CONSTRAINT `holding_fk_1` FOREIGN KEY (`BranchID`) REFERENCES `holding` (`BranchID`) ON DELETE RESTRICT
what dms are you using? could be that you need to use another syntax to reference two foreign key at one or could be that it's not supported.
As said in the answer, just by changing order can fix it.
"Your code fails in Mysql 8.0.12 but runs fine in 8.0.22 As a workaround reverse the order of the columns: CONSTRAINT holding_fk_1 FOREIGN KEY (BranchID,BookID) REFERENCES holding (BranchID,BookID) ON DELETE RESTRICT, –
forpas
Oct 27 '20 at 15:50 "

Table in mySQL that has several foreign keys that are primary key, getting an error ERROR 1215: Cannot add foreign key constraint

I had created those tables:
CREATE TABLE `course` (
`idcourse` varchar(2) NOT NULL,
`courseName` varchar(45) NOT NULL,
`subjectID` varchar(2) NOT NULL,
PRIMARY KEY (`idcourse`),
KEY `subjectID_idx` (`subjectID`),
CONSTRAINT `subjectID` FOREIGN KEY (`subjectID`) REFERENCES `subject` (`idsubject`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1
CREATE TABLE `exam` (
`subjectID` varchar(2) NOT NULL,
`courseID` varchar(2) NOT NULL,
`examNumber` varchar(2) NOT NULL,
`duration` int(11) DEFAULT NULL,
PRIMARY KEY (`subjectID`,`courseID`,`examNumber`),
KEY `idCourse_idx` (`courseID`),
CONSTRAINT `idCo` FOREIGN KEY (`courseID`) REFERENCES `course` (`idcourse`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `idSu` FOREIGN KEY (`subjectID`) REFERENCES `subject` (`idsubject`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1
CREATE TABLE `question` (
`questionText` varchar(100) DEFAULT NULL,
`answer1` varchar(100) DEFAULT NULL,
`answer2` varchar(100) DEFAULT NULL,
`answer3` varchar(100) DEFAULT NULL,
`answer4` varchar(100) DEFAULT NULL,
`subjetID` varchar(2) NOT NULL,
`questionNumber` varchar(3) NOT NULL,
`rightAnswer` int(4) DEFAULT NULL,
PRIMARY KEY (`subjetID`,`questionNumber`),
CONSTRAINT `idsubject` FOREIGN KEY (`subjetID`) REFERENCES `subject` (`idsubject`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1
CREATE TABLE `subject` (
`idsubject` varchar(2) NOT NULL,
`subjectName` varchar(45) NOT NULL,
PRIMARY KEY (`idsubject`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
To subject table I add a record:
idsubject = 02, subjectName = Mathematica
To course table I add a record:
idcourse = 03, courseName = Algebra 1, subjectID = 02
To exam table I add a record:
subjectID = 02, courseID = 03, examNumber = 01, duration = 180
Now, I want to create a table: questionsinexam
CREATE TABLE `test`.`questionsinexam` (
`idExamSubject` VARCHAR(2) NOT NULL,
`idExamCourse` VARCHAR(2) NOT NULL,
`idExamNumber` VARCHAR(2) NOT NULL,
`idQuestionNumber` VARCHAR(3) NOT NULL,
`pointsPerQuestion` INT NULL,
PRIMARY KEY (`idExamSubject`, `idExamCourse`, `idExamNumber`, `idQuestionNumber`),
INDEX `idExamCourse_idx` (`idExamCourse` ASC),
INDEX `idExamNumber_idx` (`idExamNumber` ASC),
INDEX `idQuestionNumber_idx` (`idQuestionNumber` ASC),
CONSTRAINT `idExamSubject`
FOREIGN KEY (`idExamSubject`)
REFERENCES `test`.`exam` (`subjectID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `idExamCourse`
FOREIGN KEY (`idExamCourse`)
REFERENCES `test`.`exam` (`courseID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `idExamNumber`
FOREIGN KEY (`idExamNumber`)
REFERENCES `test`.`exam` (`examNumber`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `idQuestionNumber`
FOREIGN KEY (`idQuestionNumber`)
REFERENCES `test`.`question` (`questionNumber`)
ON DELETE NO ACTION
ON UPDATE NO ACTION);
Why I'm getting this error?
Thanks.
This constraint is definitely wrong:
CONSTRAINT `idExamSubject`
FOREIGN KEY (`idExamSubject`)
REFERENCES `test`.`exam` (`subjectID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
Perhaps you intend:
CONSTRAINT `idExamSubject`
FOREIGN KEY (`idExamSubject`)
REFERENCES `test`.`subject` (`subjectID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
Be sure that you create the target tables before you create the foreign key constraint. The referred to table needs to exist first (so the engine can validate types on the columns used for the foreign key).

MySQL #1452 - Cannot add or update a child row

I'm begginer here, all what i'm trying to do is insert into a table field which is a foreign key, please take a look at this two tables :
Table Categorie
CREATE TABLE IF NOT EXISTS `categorie` (
`id_cat` int(2) NOT NULL AUTO_INCREMENT,
`nom_cat` varchar(20) NOT NULL,
PRIMARY KEY (`id_cat`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
and table Annonce
CREATE TABLE IF NOT EXISTS `annonce` (
`id_annonce` int(6) NOT NULL AUTO_INCREMENT,
`titre` varchar(30) NOT NULL,
`description` varchar(255) NOT NULL,
`tarif` float NOT NULL,
`deplacement` int(2) NOT NULL,
`date_creation` date NOT NULL,
`date_expiration` date NOT NULL,
`image` varchar(255) NOT NULL,
`id_cat` int(2) DEFAULT NULL,
PRIMARY KEY (`id_annonce`),
KEY `id_cat` (`id_cat`),
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
After linking the foreign key id_cat manually (ON UPDATE SET NULL ON DELETE CASCADE) that's how the db looks like
and after inserting data into Categorie table it looks like this
But unfortunately i couldn't execute this query :
INSERT INTO annonce (id_annonce, titre, description, tarif, deplacement,
date_creation, date_expiration,id_cat)
VALUES('','anything','anything',2,3,'2017-04-01','2017-04-01',2)
the error says :
1452 - Cannot add or update a child row: a foreign key constraint fails
(lametcom.annonce, CONSTRAINT annonce_ibfk_2 FOREIGN KEY (id_cat)
REFERENCES annonce (id_cat) ON DELETE SET NULL ON UPDATE CASCADE)
Can anyone help please and so sorry about my poor English i hope you can understand what i mean
Your foreign key constraint is wrong. You have
FOREIGN KEY id_cat REFERENCES annonce (id_cat)
but it should be:
FOREIGN KEY id_cat REFERENCES categorie (id_cat)
The table name in the foreign key constraint has to be the table you're linking to.

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 Foreign Key Constraint Confusion

Hey everyone, I have the following 'users' table in MySQL:
CREATE TABLE `users` (
`uid` int(11) NOT NULL auto_increment,
`fname` varchar(50) NOT NULL,
`lname` varchar(50) NOT NULL,
`role` varchar(75) NOT NULL,
`region` tinyint(4) unsigned default NULL,
`username` varchar(25) NOT NULL,
`password` varchar(75) NOT NULL,
`new_pass` varchar(5) default NULL,
PRIMARY KEY (`uid`),
UNIQUE KEY `username` (`username`),
KEY `role` (`role`),
KEY `region` (`region`),
CONSTRAINT `users_ibfk_3` FOREIGN KEY (`role`) REFERENCES `role` (`role`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `users_ibfk_4` FOREIGN KEY (`region`) REFERENCES `region` (`region`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=43 DEFAULT CHARSET=utf8
I have 'region' set as a foreign key to a region table - region.region'
Notice, that users.region is declared as NULL. I was under the impression that in MySQL, a foreign key contstraint is enforced ONLY if the key is set as NOT NULL.
However, when I try to insert a user with a NULL region in my PHP application, I get the following error:
ERROR: Cannot add or update a child row: a foreign key constraint fails (`reslife4/users`, CONSTRAINT `users_ibfk_4` FOREIGN KEY (`region`) REFERENCES `region` (`region`) ON DELETE CASCADE ON UPDATE CASCADE)
BUT, if I were to add this user outside of my PHP application, for example in phpMyAdmin, it would allow me to.
Does anyone know what's going on?
Your application puts a non-NULL value into region.
Enable the query log and see what exactly your PHP tries to insert into the table.