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.
Related
I have three tables user, department, and department_hod
user has a department_id, which is the primary key of department, also departement has hod which is the primary key of user.
But i am getting an error when adding the foreign key constraint of username in department_hod table,
Please help
--
-- Create a user table
--
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`username` varchar(50) NOT NULL,
`password` char(80) NOT NULL,
`emp_id` int(11) NOT NULL,
`designation` varchar(50) NOT NULL,
`department_id` int(11) NOT NULL,
`status` varchar(2) NOT NULL DEFAULT 'A',
`email_id` varchar(50) NOT NULL,
`account_status` varchar(2) NOT NULL DEFAULT 'U',
`validity_date` TIMESTAMP,
`deactivation_date` TIMESTAMP ,
`deactivated_by` varchar(50),
`deactivation_remarks` varchar(1000),
`creation_date` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`updation_date` TIMESTAMP,
`created_by` varchar(50),
`updated_by` varchar(50),
CONSTRAINT `PK_USER_ID` PRIMARY KEY (`id`,`username`),
KEY `FK_DEPARTMENT_IDX_01` (`department_id`),
CONSTRAINT `FK_DEPARTMENT_ID_01` FOREIGN KEY (`department_id`)
REFERENCES `department` (`id`)
ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
--
-- Create a department table
--
CREATE TABLE `department` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`status` varchar(2) NOT NULL DEFAULT 'A',
`creation_date` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`updation_date` TIMESTAMP,
`created_by` varchar(50),
`updated_by` varchar(50),
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
--
-- Add department_hod table
--
CREATE TABLE `department_hod` (
`department_id` int(11) NOT NULL,
`username` varchar(50) NOT NULL,
PRIMARY KEY (`username`,`department_id`),
KEY `FK_DEPARTMENT_idx_02` (`department_id`),
CONSTRAINT `FK_DEPARTMENT_id_02` FOREIGN KEY (`department_id`)
REFERENCES `department` (`id`)
ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `FK_USER_01` FOREIGN KEY (`username`)
REFERENCES `user` (`username`)
ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
SET FOREIGN_KEY_CHECKS = 1;
error is here
CONSTRAINT `FK_USER_01` FOREIGN KEY (`username`)
REFERENCES `user` (`username`)
ON DELETE NO ACTION ON UPDATE NO ACTION
Error is
Error Code: 1215. Cannot add foreign key constraint
Always provide complete error message. In a half of choices you may find the solution in it.
For your code the error message is
Failed to add the foreign key constraint. Missing index for constraint 'FK_USER_01' in the referenced table 'user'
So the problem can be fixed by absent index creation:
CREATE INDEX idx_user_username ON user (username);
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=1f0fd24a8eb9cb5692b9d35dd1903045
can you please tell me that is it necessary to use index here? as it is only used for speeding up, do i have to use it beacuse of two primary keys in my user table? – shah-123
MySQL 8.0 Reference Manual / ... / FOREIGN KEY Constraints / Conditions and Restrictions
MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist. This index might be silently dropped later if you create another index that can be used to enforce the foreign key constraint. index_name, if given, is used as described previously.
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,
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.
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?
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.