MySQL: Cannot add or update a child row: a foreign key constraint fails - mysql

I have a workflow in my application where an admin for an organization can add a user to their organization. Once a form submission, I first insert a new record into my user table with the users email and the organization id associated with the admin. After that user is created, a member record which connects the user to the organization is created with the users email and the users organization id and user_id. The issue I am running into is with creating a record on the member table with the recently created users user_id. While I have no issue storing the organization_id present, for some reason passing the user_id throws an error related to the foreign key:
Cannot add or update a child row: a foreign key constraint fails (`work`.`member`, CONSTRAINT `member_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `organization` (`organization_id`) ON DELETE CASCADE ON UPDATE CASCADE)]
Why can't I pass the user_id on record creation. Is it because the column is associated to a foreign key?
Here are the inserts:
User insert (No error):
INSERT INTO `user` (`user_id`,`email`,`organization_id`,`updatedAt`,`createdAt`) VALUES (DEFAULT,'test+email#gmail.com','1','2016-06-07 11:51:54','2016-06-07 11:51:54');
Member insert (Error with user_id):
INSERT INTO `member` (`member_id`,`member_email`,`organization_id`,`user_id`,`updatedAt`,`createdAt`) VALUES (DEFAULT,'test+email#gmail.com','1',8,'2016-06-07 11:51:54','2016-06-07 11:51:54');
User Table:
`user` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(255) DEFAULT NULL,
`last_name` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`organization_id` int(11) DEFAULT NULL,
`authentication_token` varchar(255) DEFAULT NULL,
`reset_password_token` varchar(255) DEFAULT NULL,
`reset_password_expires` datetime DEFAULT NULL,
`createdAt` datetime NOT NULL,
`updatedAt` datetime NOT NULL,
PRIMARY KEY (`user_id`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
Organization table:
`organization` (
`organization_id` int(11) NOT NULL AUTO_INCREMENT,
`organization_name` varchar(255) DEFAULT NULL,
`admin` varchar(255) DEFAULT NULL,
`createdAt` datetime NOT NULL,
`updatedAt` datetime NOT NULL,
PRIMARY KEY (`organization_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
Member table:
`member` (
`member_id` int(11) NOT NULL AUTO_INCREMENT,
`member_email` varchar(255) DEFAULT NULL,
`organization_id` int(11) DEFAULT NULL,
`user_id` int(11) DEFAULT NULL,
`createdAt` datetime NOT NULL,
`updatedAt` datetime NOT NULL,
PRIMARY KEY (`member_id`),
UNIQUE KEY `member_email` (`member_email`),
UNIQUE KEY `member_user_id_organizationId_unique` (`organization_id`,`user_id`),
KEY `user_id` (`user_id`),
CONSTRAINT `member_ibfk_1` FOREIGN KEY (`organization_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `member_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `organization` (`organization_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;

Seem to me that you got your constraints mixed up.
I created the tables using your sql and reverse engineered with MySQLWorkbench to get an EER containing your tables.
On first sight you can see that organization_id in table organization is linked with user_id in members table.
If you change your constraints to the following, it will work:
CONSTRAINT `member_ibfk_1` FOREIGN KEY (`organization_id`) REFERENCES `organization` (`organization_id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `member_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE

Try to change the CONSTRAINT member_ibfk_1 to this:
CONSTRAINT `member_ibfk_1` FOREIGN KEY (`organization_id`) REFERENCES user(`user_id`) ON DELETE CASCADE ON UPDATE CASCADE,

Related

Foreign key constraint fails when I want delete table

When I am trying
drop tables users;
It shows error: Cannot delete or update a parent row: a foreign key constraint fails
Here are my tables:
CREATE TABLE `events` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(128) NOT NULL,
`users_id` int(11) NOT NULL,
`capacity` int(64) NOT NULL,
`event_date` datetime NOT NULL,
`text` text CHARACTER SET utf8 COLLATE utf8_czech_ci,
`last_edit` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `users_id` (`users_id`),
CONSTRAINT `events_ibfk_5` FOREIGN KEY (`users_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL,
`role` enum('admin','member','guest','registered') NOT NULL DEFAULT 'registered',
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `users_data` (
`id` int(120) NOT NULL AUTO_INCREMENT,
`users_id` int(11) DEFAULT NULL,
`name` varchar(50) NOT NULL,
`username` varchar(50) NOT NULL,
`phone_number` varchar(25) NOT NULL,
PRIMARY KEY (`id`),
KEY `users_id` (`users_id`),
CONSTRAINT `users_data_ibfk_5` FOREIGN KEY (`users_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `user_matches` (
`user_id` int(120) NOT NULL,
`match_id` int(11) NOT NULL,
KEY `user_id` (`user_id`),
KEY `match_id` (`match_id`),
CONSTRAINT `user_matches_ibfk_4` FOREIGN KEY (`user_id`) REFERENCES `users_data` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `user_matches_ibfk_5` FOREIGN KEY (`match_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I think I did wrong foreign key but I am not sure how to change it correctly. Thank you for your any advice.
When you submit drop table users MySQL checks for referential integrity constraints violation when the deletion is about to be committed. This check fails because you have defined the following constraint of events:
CONSTRAINTevents_ibfk_5FOREIGN KEY (users_id) REFERENCESusers(id) ON DELETE CASCADE ON UPDATE CASCADE
and at the same time on the events table the users_id field cannot be NULL. Therefore, upon dropping the table, the users_id is set to NULL which fails during commit. One possible way to work around this problem is to remove the NOT NULL constraint on the users_id field on the events table.

Error when updating with foreign keys with ON UPDATE CASCADE

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?

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.

MYSQL: Cannot add or update a child row: a foreign key constraint fails

I am getting the error:
Cannot add or update a child row: a foreign key constraint fails (mydb/requests, CONSTRAINT requests_ibfk_5 FOREIGN KEY (fixture_id) REFERENCES fixtures (fix_id) ON UPDATE CASCADE ON DELETE CASCADE)
I have the following table structure:
CREATE TABLE IF NOT EXISTS `requests` (
`request_id` int(11) unsigned NOT NULL auto_increment,
`fixture_id` int(11) unsigned NOT NULL,
`user_id` int(11) unsigned NOT NULL,
`date_added` datetime NOT NULL,
`date_modified` datetime default NULL,
PRIMARY KEY (`request_id`),
UNIQUE KEY `fixture_id_2` (`fixture_id`,`user_id`),
KEY `user_id` (`user_id`),
KEY `date_added` (`date_added`),
KEY `fixture_id` (`fixture_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=17 ;
CREATE TABLE IF NOT EXISTS `fixtures` (
`id` int(11) unsigned NOT NULL auto_increment,
`fix_id` int(11) unsigned NOT NULL default '0',
`fixture_date` date default NULL,
`kickoff` time default NULL,
`venue` varchar(35) default NULL,
`home_score` tinyint(4) default NULL,
`away_score` tinyint(4) default NULL,
`date_added` datetime default NULL,
`date_modified` datetime default NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `fix_id` (`fix_id`),
KEY `fixture_date` (`fixture_date`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=383 ;
ALTER TABLE `requests`
ADD CONSTRAINT `requests_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`) ON DELETE CASCADE,
ADD CONSTRAINT `requests_ibfk_5` FOREIGN KEY (`fixture_id`) REFERENCES `fixtures` (`fix_id`) ON DELETE CASCADE ON UPDATE CASCADE;
If I update a record on the fix_id field the parent table (fixtures), that has a shared id (fixture_id) in the child table (requests) I get the above error.
I cannot see why this integrity constraint is failing. Both tables already have the correct data it should cascade through?
Any help greatly appreciated.
This was all my own error. I had two foreign constraints on the same field in reality. I just needed to take one off.
This error occurs due to the reference of other table, in both tables same id's/data should exist. If not please use where conditions to remove not existing data.
example
update tablename a set = 'field' (select field from othertable b) where a.data = b.data;

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.