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 "
Related
I have 2 tables like these:
'CREATE TABLE `preoperativeassessments` (
`Id` char(36) NOT NULL,
`SurgeonName` varchar(100) NOT NULL,
`SurgeonExperience` int(11) DEFAULT NULL,
`AnesthetistName` varchar(100) DEFAULT NULL,
`DateOfBirthYear` int(11) DEFAULT NULL,
`Gender` int(11) DEFAULT NULL,
`Status` int(11) DEFAULT NULL,
`SurgeryDate` datetime(6) DEFAULT NULL,
`HospitalId` varchar(20) NOT NULL,
`PatientId` varchar(50) NOT NULL,
`SurgeonId` bigint(20) NOT NULL,
`TheaterId` varchar(16) DEFAULT NULL,
`AssessmentDate` datetime(6) DEFAULT NULL,
`BodyStructureId` int(11) NOT NULL,
`MethodId` varchar(100) DEFAULT NULL,
`EthnicityId` int(11) DEFAULT NULL,
PRIMARY KEY (`Id`),
KEY `FK_PreOperativeAssessments_Hospitals_HospitalId_idx` (`HospitalId`),
KEY `FK_PreOperativeAssessments_Patients_PatientId_idx` (`PatientId`),
KEY `FK_PreOperativeAssessments_Users_SurgeonId_idx` (`SurgeonId`),
KEY `FK_PreOperativeAssessments_BodyStructures_BodyStructureId_idx` (`BodyStructureId`),
CONSTRAINT `FK_PreOperativeAssessments_BodyStructures_BodyStructureId` FOREIGN KEY (`BodyStructureId`) REFERENCES `bodystructures` (`Id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `FK_PreOperativeAssessments_Hospitals_HospitalId` FOREIGN KEY (`HospitalId`) REFERENCES `hospitals` (`Id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `FK_PreOperativeAssessments_Patients_PatientId` FOREIGN KEY (`PatientId`) REFERENCES `patients` (`Id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `FK_PreOperativeAssessments_Users_SurgeonId` FOREIGN KEY (`SurgeonId`) REFERENCES `abpusers` (`Id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1'
CREATE TABLE `ethnicities` (
`Id` int(11) NOT NULL,
`Description` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1
and I try to add foreign key constraint using this:
ALTER TABLE casemix.preoperativeassessments ADD CONSTRAINT FK_PreOperativeAssessments_Ethnicities_EthnicityId FOREIGN KEY (EthnicityId) REFERENCES casemix.ethnicities (Id) ON UPDATE NO ACTION ON DELETE CASCADE
But I keep getting this error: "Error Code: 1215. Cannot add foreign key constraint"
What could be the issue here?
'InnoDB permits a foreign key to reference any index column or group of columns. However, in the referenced table, there must be an index where the referenced columns are the first columns in the same order.' - https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html or a primary key
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).
I have these two simple table
CREATE TABLE `location_main_master` (
`location_main_master_id` bigint(16) unsigned NOT NULL,
`city_id_test` int(10) unsigned NOT NULL,
PRIMARY KEY (`location_main_master_id`,`city_id_test`),
UNIQUE KEY `location_main_master_id_UNIQUE` (`location_main_master_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `location_sub_master` (
`location_sub_master_id` bigint(16) unsigned NOT NULL,
`city_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`location_sub_master_id`,`city_id`),
UNIQUE KEY `location_sub_master_id_UNIQUE` (`location_sub_master_id`),
KEY `fk_location_sub_master_city_id_idx` (`city_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I'm trying to add a foreign key
ALTER TABLE `location_sub_master`
ADD CONSTRAINT `fk_location_sub_city_id`
FOREIGN KEY (`city_id`)
REFERENCES `location_main_master` (`city_id_test`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
It give me this ERROR :
ERROR 1215: Cannot add foreign key constraint
You have to change the order of your primary key in master table.
PRIMARY KEY (city_id_test,location_main_master_id)
So your master table should look like
CREATE TABLE location_main_master (
location_main_master_id BIGINT(16) UNSIGNED NOT NULL,
city_id_test INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (city_id_test,location_main_master_id),
UNIQUE KEY location_main_master_id_UNIQUE (location_main_master_id)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
| section | CREATE TABLE `section` (
`CourseNumber` varchar(10) NOT NULL,
`Quarter` varchar(10) NOT NULL,
`RoomNumber` varchar(4) DEFAULT NULL,
`DayTime` varchar(20) DEFAULT NULL,
PRIMARY KEY (`CourseNumber`,`Quarter`),
CONSTRAINT `section_ibfk_1` FOREIGN KEY (`CourseNumber`) REFERENCES `Course` (`CourseNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
| enrollment | CREATE TABLE `enrollment` (
`SSN` varchar(9) DEFAULT NULL,
`CourseNumber` varchar(4) DEFAULT NULL,
`Quarter` varchar(10) DEFAULT NULL,
`Grade` varchar(1) DEFAULT NULL,
KEY `SSN` (`SSN`),
KEY `CourseNumber` (`CourseNumber`),
CONSTRAINT `enrollment_ibfk_1` FOREIGN KEY (`SSN`) REFERENCES `Student` (`SSN`),
CONSTRAINT `enrollment_ibfk_2` FOREIGN KEY (`CourseNumber`) REFERENCES `Course` (`CourseNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
mysql> alter table enrollment add foreign key(Quarter) references section(Quarter);
ERROR 1215 (HY000): Cannot add foreign key constraint
Column Quarter in both table Enrollment and Section have the datatype VARCHAR(10),so I am not sure what is causing the error.
If tables have data which do not respect foreign key you can not create it.
Try
SET foreign_key_checks = 0;
alter table enrollment add foreign key(Quarter) references section(Quarter);
SET foreign_key_checks = 1;
But i have used this to delete tables, do not know what will happen in this case.
This is a two fold problem...
Column Quarter is not already indexed in the target table enrollment.
Column Quarter is also not indexed in the source table section, although it is a part of the composite PRIMARY KEY along with CourseNumber.
So, if you just want Quarter from section table to be referenced in enrollment table, you'd need to:
ALTER TABLE `section` ADD INDEX( `Quarter`);
ALTER TABLE `enrollment` ADD INDEX( `Quarter`);
And thereafter:
ALTER TABLE enrollment ADD FOREIGN KEY(`Quarter`) REFERENCES section(`Quarter`);
However, if you want (CourseNumber, Quarter) as a composite foreign key, you would need to create a combined index on the two fields in enrollment table:
ALTER TABLE `enrollment` ADD INDEX( `CourseNumber`, `Quarter`);
And follow it up with:
ALTER TABLE `enrollment` ADD FOREIGN KEY( `CourseNumber`, `Quarter` )
REFERENCES section( `CourseNumber`, `Quarter` );
Must be some data preventing the creation as others have said. This worked fine when I ran it:
CREATE TABLE `Course` (
`CourseNumber` varchar(10) NOT NULL,
PRIMARY KEY (`CourseNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `Student` (
`SSN` varchar(9) NOT NULL,
PRIMARY KEY (`SSN`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `section` (
`CourseNumber` varchar(10) NOT NULL,
`Quarter` varchar(10) NOT NULL,
`RoomNumber` varchar(4) DEFAULT NULL,
`DayTime` varchar(20) DEFAULT NULL,
PRIMARY KEY (`CourseNumber`,`Quarter`),
CONSTRAINT `section_ibfk_1` FOREIGN KEY (`CourseNumber`) REFERENCES `Course` (`CourseNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `enrollment` (
`SSN` varchar(9) DEFAULT NULL,
`CourseNumber` varchar(4) DEFAULT NULL,
`Quarter` varchar(10) DEFAULT NULL,
`Grade` varchar(1) DEFAULT NULL,
KEY `SSN` (`SSN`),
KEY `CourseNumber` (`CourseNumber`),
CONSTRAINT `enrollment_ibfk_1` FOREIGN KEY (`SSN`) REFERENCES `Student` (`SSN`),
CONSTRAINT `enrollment_ibfk_2` FOREIGN KEY (`CourseNumber`) REFERENCES `Course` (`CourseNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I have this table:
CREATE TABLE `user` (
`idUser` char(13) NOT NULL,
`contrasena` varchar(50) NOT NULL DEFAULT '',
`fechaInicio` datetime DEFAULT NULL,
`emailRegistrado` varchar(100) DEFAULT NULL,
`tipoUsuario` int(11) NOT NULL,
PRIMARY KEY (`idUser`),
KEY `tipoUser` (`tipoUsuario`) USING BTREE,
CONSTRAINT `tipoUser` FOREIGN KEY (`tipoUsuario`) REFERENCES `tipo_user` (`idTipo`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf16;
And then this table:
CREATE TABLE `alumno` (
`idAlumno` char(10) NOT NULL DEFAULT '',
`Nombre` varchar(60) NOT NULL,
`ApePaterno` varchar(30) NOT NULL,
`ApeMaterno` varchar(30) NOT NULL,
`CURP` varchar(18) DEFAULT NULL,
`Sexo` enum('H','M') NOT NULL,
`FechaNac` date NOT NULL,
`Estado_Nac` int(11) DEFAULT NULL,
`Nacionalidad` int(11) DEFAULT NULL,
PRIMARY KEY (`idAlumno`),
KEY `fk_Alumno_Estados1_idx` (`Estado_Nac`) USING BTREE,
KEY `fk_Alumno_Pais1_idx` (`Nacionalidad`) USING BTREE,
CONSTRAINT `fk_Alumno_Estados1` FOREIGN KEY (`Estado_Nac`) REFERENCES `estadomexico` (`idEstados`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_Alumno_Pais1` FOREIGN KEY (`Nacionalidad`) REFERENCES `pais` (`idPais`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_Al_User` FOREIGN KEY (`idAlumno`) REFERENCES `user` (`idUser`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf16;
When I try to update a value for a user, MySQL throws the following message:
Cannot delete or update a parent row: a foreign key constraint fails (mydb.empleado, CONSTRAINT fk_Empleado_USer FOREIGN KEY
(idEmpleado) REFERENCES user (idUser) ON DELETE CASCADE ON
UPDATE CASCADE)
Can anybody please help me?