Error when updating with foreign keys with ON UPDATE CASCADE - mysql

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?

Related

Unable to create foreign key constraint MySql

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

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 Error Code: 1451 Can't Delete or Update Parent Row

I have a self join in the channels table with the field parent_id. I have inserted a row into the table but unable to delete it. Its giving error as stated in the subject.
CREATE TABLE `channels` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`image` int(11) DEFAULT NULL,
`parent_id` int(11) DEFAULT NULL,
`channel_type_id` int(11) DEFAULT NULL,
`approval_type_id` int(11) DEFAULT NULL,
`content_type_id` int(11) DEFAULT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
`status` tinyint(1) NOT NULL,
`position` int(11) DEFAULT NULL,
`reference_id` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
`mobile` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `IDX_F314E2B6C53D045F` (`image`),
KEY `IDX_F314E2B6727ACA70` (`parent_id`),
KEY `IDX_F314E2B6720FB392` (`channel_type_id`),
KEY `IDX_F314E2B6510C33D5` (`approval_type_id`),
KEY `IDX_F314E2B61A445520` (`content_type_id`),
CONSTRAINT `FK_F314E2B6727ACA70` FOREIGN KEY (`parent_id`) REFERENCES `channels` (`id`),
CONSTRAINT `FK_F314E2B61A445520` FOREIGN KEY (`content_type_id`) REFERENCES `content_type` (`id`),
CONSTRAINT `FK_F314E2B6510C33D5` FOREIGN KEY (`approval_type_id`) REFERENCES `approval_types` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `FK_F314E2B6720FB392` FOREIGN KEY (`channel_type_id`) REFERENCES `channel_types` (`id`),
CONSTRAINT `FK_F314E2B6C53D045F` FOREIGN KEY (`image`) REFERENCES `media__media` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6438 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
The error is as following:
Error Code: 1451. Cannot delete or update a parent row: a foreign key constraint fails (`wenweipo`.`channels`, CONSTRAINT `FK_F314E2B6727ACA70` FOREIGN KEY (`parent_id`) REFERENCES `channels` (`id`))

MySQL 5.1 not accepting null foreign key from Access 2007

Backend - MySQL 5.1.52 community
Frontend - MS Access 2007
I've got two tables POLIZAS and TRAMITES (both InnoDB)
I'm using Access as the FrontEnd. I need to insert/update records on Tramites where sometimes Tramites is not related to a Polizas yet.
Tramites has a foreign key to Polizas allowing null. But still I get this error when inserting/updating:
[MySQL][ODBC 5.1 Driver][mysqld-5.1.52-community]Cannot add or update a child row: a foreign key constraint fails ('cartera_bd'.'tramites',CONSTRAINT 'fk_tramites_polizas1' FOREIGN KEY ('Poliza') REFERENCES 'polizas' ('Poliza') ON DELETE CASCADE ON UPDATE CASCADE) (#1452)
Any clues?
This is the POLIZAS table description
CREATE TABLE `polizas` (
`Poliza` varchar(20) NOT NULL,
`IdAgente` mediumint(8) unsigned NOT NULL,
`IdPlan` tinyint(3) unsigned NOT NULL,
`IdCliente` int(10) unsigned NOT NULL,
`RenuevaA` varchar(20) DEFAULT NULL,
`InicioVigencia` date NOT NULL,
`IdTipoDerechos` tinyint(1) unsigned NOT NULL,
`IdConducto` tinyint(1) unsigned NOT NULL,
`IdFormaPago` tinyint(1) unsigned NOT NULL,
`IdMoneda` tinyint(1) unsigned NOT NULL,
`PrimaNeta` decimal(11,2) NOT NULL,
`Recargos` decimal(11,2) DEFAULT NULL,
`Derechos` decimal(11,2) DEFAULT NULL,
`IVA` decimal(11,2) DEFAULT NULL,
`PrimaTotal` decimal(11,2) NOT NULL,
`Status` tinyint(1) unsigned NOT NULL,
`Notas` varchar(150) DEFAULT NULL,
`FechaEmision` date DEFAULT NULL,
PRIMARY KEY (`Poliza`),
KEY `IdAgente` (`IdAgente`),
KEY `IdCliente` (`IdCliente`),
KEY `IdConducto` (`IdConducto`),
KEY `IdFormaPago` (`IdFormaPago`),
KEY `IdMoneda` (`IdMoneda`),
KEY `IdPlan` (`IdPlan`),
KEY `IdTipoDerechos` (`IdTipoDerechos`),
KEY `fk_polizas_status1` (`Status`),
CONSTRAINT `fk_polizas_agentes1` FOREIGN KEY (`IdAgente`) REFERENCES `agentes` (`ID`) ON DELETE NO ACTION ON UPDATE CASCADE,
CONSTRAINT `fk_polizas_clientes1` FOREIGN KEY (`IdCliente`) REFERENCES `clientes` (`ID`) ON DELETE NO ACTION ON UPDATE CASCADE,
CONSTRAINT `fk_polizas_conducto1` FOREIGN KEY (`IdConducto`) REFERENCES `conducto` (`ID`) ON DELETE NO ACTION ON UPDATE CASCADE,
CONSTRAINT `fk_polizas_formapago1` FOREIGN KEY (`IdFormaPago`) REFERENCES `formapago` (`ID`) ON DELETE NO ACTION ON UPDATE CASCADE,
CONSTRAINT `fk_polizas_moneda1` FOREIGN KEY (`IdMoneda`) REFERENCES `moneda` (`ID`) ON DELETE NO ACTION ON UPDATE CASCADE,
CONSTRAINT `fk_polizas_planes1` FOREIGN KEY (`IdPlan`) REFERENCES `planes` (`ID`) ON DELETE NO ACTION ON UPDATE CASCADE,
CONSTRAINT `FK_polizas_status1` FOREIGN KEY (`Status`) REFERENCES `status` (`ID`) ON DELETE NO ACTION ON UPDATE CASCADE,
CONSTRAINT `fk_polizas_tipoderechos1` FOREIGN KEY (`IdTipoDerechos`) REFERENCES `tipoderechos` (`ID`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
This is the TRAMITES table description
CREATE TABLE `tramites` (
`IdTramite` int(11) NOT NULL AUTO_INCREMENT,
`IdTipoTramite` tinyint(1) unsigned NOT NULL,
`Folio` int(11) DEFAULT NULL,
`Poliza` varchar(20) DEFAULT NULL,
`Inicio` date NOT NULL,
`Fin` date DEFAULT NULL,
`Tramite` text,
`Dias` int(11) DEFAULT NULL,
`IdCliente` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`IdTramite`),
KEY `fk_tramites_polizas1` (`Poliza`),
KEY `fk_tramites_tipotramite1` (`IdTipoTramite`),
KEY `fk_tramites_clientes1` (`IdCliente`) USING BTREE,
CONSTRAINT `fk_tramites_polizas1` FOREIGN KEY (`Poliza`) REFERENCES `polizas` (`Poliza`) ON DELETE NO ACTION ON UPDATE CASCADE,
CONSTRAINT `fk_tramites_tipotramite1` FOREIGN KEY (`IdTipoTramite`) REFERENCES `tipotramite` (`Id`) ON DELETE NO ACTION ON UPDATE CASCADE,
CONSTRAINT `FK_tramite_clientes1` FOREIGN KEY (`IdCliente`) REFERENCES `clientes` (`ID`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

MySQL error when trying to truncate table

I'm having problems to truncate a table on the MySQL Server 5.5.
The table I'm trying to truncate has a column that serves as a foreign key in another table.
The CREATE TABLE of both tables involved is as it follows:
CREATE TABLE `tbluser` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`creationDate` datetime NOT NULL,
`creationUserId` int(11) NOT NULL,
`updateDate` datetime NOT NULL,
`updateUserId` int(11) NOT NULL,
`lastAccess` datetime NOT NULL,
`enabled` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`),
UNIQUE KEY `email_UNIQUE` (`email`),
KEY `FK_tbluser_creationUserId` (`creationUserId`),
KEY `FK_tbluser_updateUserId` (`updateUserId`),
CONSTRAINT `FK_tbluser_updateUserId` FOREIGN KEY (`updateUserId`) REFERENCES `tbluser` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `FK_tbluser_creationUserId` FOREIGN KEY (`creationUserId`) REFERENCES `tbluser` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
CREATE TABLE `tblpost` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`content` mediumtext NOT NULL,
`creationDate` datetime NOT NULL DEFAULT '1901-01-01 00:00:00',
`creationUserId` int(11) NOT NULL,
`updateDate` datetime NOT NULL DEFAULT '1901-01-01 00:00:00',
`updateUserId` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_tblpost_creationUserId` (`creationUserId`),
KEY `FK_tblpost_updateUserId` (`updateUserId`),
CONSTRAINT `FK_tblpost_updateUserId` FOREIGN KEY (`updateUserId`) REFERENCES `tbluser` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `FK_tblpost_creationUserId` FOREIGN KEY (`creationUserId`) REFERENCES `tbluser` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Please note that all the constraints are both set to DELETE and UPDATE ON CASCADE.
When I try to TRUNCATE the table:
TRUNCATE TABLE `<databasename>`.`tbluser`;
I receive the following error message:
Cannot truncate a table referenced in a foreign key constraint
(`<databasename>`.`tblpost`,
CONSTRAINT `FK_tblpost_updateUserId`
FOREIGN KEY (`updateUserId`)
REFERENCES `<databasename>`.`tbluser` (`id`))
In addition to this information, there is the fact that when the action above is attempted on a MySQL Server 5.1, it works!
Does anyone have an idea of why this is happening?
Check here . That makes sense that TRUNCATE TABLE raises an error in such cases; the bad thing that it's not documented.