cant add or update child row, foreign key fails - mysql

This is my sql file:
DROP DATABASE IF EXISTS `dbstudents`;
CREATE DATABASE IF NOT EXISTS `dbstudents`;
USE `dbstudents`;
DROP TABLE IF EXISTS `student_detail`;
CREATE TABLE `student_detail` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`fav_programming_language` varchar(128) DEFAULT NULL,
`city` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(45) DEFAULT NULL,
`last_name` varchar(45) DEFAULT NULL,
`email` varchar(45) DEFAULT NULL,
`student_detail_id` int(11) DEFAULT NULL,
`password` varchar(50) NOT NULL,
`enabled` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_DETAIL_idx` (`student_detail_id`),
CONSTRAINT `FK_DETAIL` FOREIGN KEY (`student_detail_id`) REFERENCES `student_detail` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
DROP TABLE IF EXISTS `authorities`;
CREATE TABLE `authorities` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`authority` varchar(50) NOT NULL,
UNIQUE KEY `authorities_idx_1` (`id`,`authority`),
CONSTRAINT `authorities_ibfk_1` FOREIGN KEY (`id`) REFERENCES `student` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
This is insert statement:
INSERT INTO `student`
VALUES
(1, 'Stefan', 'Stefanovic', 'stefan#gmail.com', 1, 'stefan123', 1),
(2, 'Marko', 'Markovic', 'marko#gmail.com', 1, 'marko123', 1),
(3, 'Jovan', 'Jovanovic', 'jovan#gmail.com', 1, 'jovan123', 1);
This is error:
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`dbstudents`.`student`, CONSTRAINT `FK_DETAIL` FOREIGN KEY (`student_detail_id`) REFERENCES `student_detail` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
I found some solutions but all of them are on some way different then mine. How to solve this? An error occurs when I try to fill in every table except the autorities

As you haven't any student_details already in the system use NULL instead a number and add the number later
INSERT INTO `student`
VALUES
(1, 'Stefan', 'Stefanovic', 'stefan#gmail.com', NULL, 'stefan123', 1),
(2, 'Marko', 'Markovic', 'marko#gmail.com', NULL, 'marko123', 1),
(3, 'Jovan', 'Jovanovic', 'jovan#gmail.com', NULL, 'jovan123', 1);
see example https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=c1bbdd8ee9b9a9af244da774cdb41175

Related

Insert into a table with forign key within the trigger of the other table in MySQL

I have a parent table in MySQL as follows:
CREATE TABLE `parentTBL` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`source_name` varchar(255) DEFAULT NULL,
`loc1` smallint(5) unsigned DEFAULT NULL,
`loc2` smallint(5) unsigned DEFAULT NULL,
`extra_info` json DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=latin1;
a child table:
CREATE TABLE `childTBL` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`source_names_id` int(10) unsigned NOT NULL,
`locations_id` int(10) unsigned NOT NULL,
`extra_info` json DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_childTBL1_idx` (`source_names_id`),
KEY `fk_childTBL2_idx` (`locations_id`),
CONSTRAINT `fk_childTBL1` FOREIGN KEY (`source_names_id`) REFERENCES `source_names` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_childTBL2` FOREIGN KEY (`locations_id`) REFERENCES `locations` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
and these 2 tables:
CREATE TABLE `source_names` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`source_name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `source_name_UNIQUE` (`source_name`)
) ENGINE=InnoDB AUTO_INCREMENT=85 DEFAULT CHARSET=latin1;
CREATE TABLE `locations` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`loc1` smallint(5) unsigned DEFAULT NULL,
`loc2` smallint(5) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `loc1` (`loc1`,`loc2`)
) ENGINE=InnoDB AUTO_INCREMENT=43 DEFAULT CHARSET=latin1;
I have a trigger for parentTBL table before insert like this:
CREATE DEFINER=`root`#`localhost` TRIGGER `myDB`.`parentTBL_BEFORE_INSERT` BEFORE INSERT ON `parentTBL` FOR EACH ROW
BEGIN
INSERT IGNORE INTO source_names (source_name) VALUES (NEW.source_name);
INSERT IGNORE INTO locations (loc1,loc2) VALUES (NEW.loc1,NEW.loc2);
INSERT IGNORE INTO childTBL (source_names_id,locations_id,extra_info) VALUES (????,????,NEW.extra_info);
END
and I want to insert into childTBL and 2 other tables before inserting into parentTBL but I don't know what should I put in ???? fields in above trigger (third INSERT IGNORE. Move scroll to right)?
(It should be noted that I don't want to use SELECT because I have some millions records and fast insertion is important to me and also my problem is not solved with LAST_INSERT_ID() because it is possible that I need the source_names_id which is added before last_inserted in source_names table.)

Cannot add a foreign key in mysql where a field is a unique index

I'm having problem adding a foreign key based on AUTH_ISLE_CODE:
Create Table: CREATE TABLE `AUTH_ACCOUNT` (
`ACCOUNT_ID` int(11) NOT NULL AUTO_INCREMENT,
`PASSWORD` varchar(20) DEFAULT NULL,
...
`AUTH_ISLE_ID` int(11) NOT NULL DEFAULT '1',
`AUTH_ISLE_CODE` varchar(5) NOT NULL DEFAULT 'AAAAA',
PRIMARY KEY (`ACCOUNT_ID`),
KEY `fk_ACCOUNT_ISLE` (`AUTH_ISLE_ID`),
CONSTRAINT `fk_ACCOUNT_ISLE` FOREIGN KEY (`AUTH_ISLE_ID`) REFERENCES `AUTH_ISLE` (`ISLE_ID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=166 DEFAULT CHARSET=utf8
Create Table: CREATE TABLE `AUTH_ISLE` (
`ISLE_ID` int(11) NOT NULL AUTO_INCREMENT,
`NAME` varchar(100) DEFAULT NULL,
`CODE` varchar(5) NOT NULL DEFAULT 'AAAAA',
PRIMARY KEY (`ISLE_ID`),
UNIQUE KEY `CODE_UNIQUE` (`CODE`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8
the error I'm having is:
ERROR 1005 (HY000): Can't create table 'masterdata.#sql-73c1_57910' (errno: 150)
Is it something about the fact that the two tables have already a relationship with AUTH_ISLE_ID
Edit 1: the SHOW CREATE TABLE you see is the current situation. I'm trying to add just the constraint to AUTH_ISLE_CODE -> CODE from AUTH_ISLE
If this is a sequence of queries you are trying to create tables then it will always fail because you are referencing a table REFERENCES AUTH_ISLE (ISLE_ID) which is not created yet ,try creating first AUTH_ISLE table then create your second table AUTH_ACCOUNT,and when AUTH_ISLE is present you can simply reference its columns
CREATE TABLE `AUTH_ISLE` (
`ISLE_ID` int(11) NOT NULL AUTO_INCREMENT,
`NAME` varchar(100) DEFAULT NULL,
`CODE` varchar(5) NOT NULL DEFAULT 'AAAAA',
PRIMARY KEY (`ISLE_ID`),
UNIQUE KEY `CODE_UNIQUE` (`CODE`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
CREATE TABLE `AUTH_ACCOUNT` (
`ACCOUNT_ID` int(11) NOT NULL AUTO_INCREMENT,
`PASSWORD` varchar(20) DEFAULT NULL,
`AUTH_ISLE_ID` int(11) NOT NULL DEFAULT '1',
`AUTH_ISLE_CODE` varchar(5) NOT NULL DEFAULT 'AAAAA',
PRIMARY KEY (`ACCOUNT_ID`),
KEY `fk_ACCOUNT_ISLE` (`AUTH_ISLE_ID`),
CONSTRAINT `fk_ACCOUNT_ISLE` FOREIGN KEY (`AUTH_ISLE_ID`)
REFERENCES `AUTH_ISLE` (`ISLE_ID`)
ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=166 DEFAULT CHARSET=utf8;
Demo
insert into AUTH_ISLE (NAME,CODE) values('Test','Test');
insert into AUTH_ACCOUNT (PASSWORD,AUTH_ISLE_ID,AUTH_ISLE_CODE)
values('Test',last_insert_id(),'Test');
Insert Demo

how to get autoincrement ID of one table and insert in another table

I have a mysql table whose description is given below
Create Table
CREATE TABLE `question` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`category` varchar(255) DEFAULT NULL,
`is_deleted` bit(1) NOT NULL,
`question` varchar(255) DEFAULT NULL,
`version` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8
I have another table
Create Table
CREATE TABLE `parent_question` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`is_deleted` bit(1) NOT NULL,
`version` int(11) DEFAULT NULL,
`pid` bigint(20) NOT NULL,
`qid` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FK8FEA83DBE860AF9` (`pid`),
KEY `FK8FEA83DBF34C20F6` (`qid`),
CONSTRAINT `FK8FEA83DBE860AF9` FOREIGN KEY (`pid`) REFERENCES `parent` (`id`),
CONSTRAINT `FK8FEA83DBF34C20F6` FOREIGN KEY (`qid`) REFERENCES `question` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8
I have the right to insert one row in the question table.So when I add a new row then id will be generated (because it is auto_increment) and I want to store this id in the qid field parent_question table.
Can anybody please tell me how to do it?
Use the last_insert_id() function:
insert into question values (...);
insert into parent_question values (..., last_insert_id(), ...);

Foreign Key Constraint error for delete data form table

i am doing a project on ONLINE EXAMINATION which is copied from my senior but while execute i got some error. attach my code here and the error msg.
table #:
CREATE TABLE IF NOT EXISTS `question` (
`testid` bigint(20) NOT NULL DEFAULT '0',
`qnid` int(11) NOT NULL DEFAULT '0',
`question` varchar(500) DEFAULT NULL,
`optiona` varchar(100) DEFAULT NULL,
`optionb` varchar(100) DEFAULT NULL,
`optionc` varchar(100) DEFAULT NULL,
`optiond` varchar(100) DEFAULT NULL,
`correctanswer` enum('optiona','optionb','optionc','optiond') DEFAULT NULL,
`marks` int(11) DEFAULT NULL,
PRIMARY KEY (`testid`,`qnid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table question
INSERT INTO `question` (`testid`, `qnid`, `question`, `optiona`, `optionb`, `optionc`, `optiond`, `correctanswer`, `marks`) VALUES
(1, 1, 'why use photoshop', 'image retouching', 'image making', 'image destroying', 'color coreection', 'optiona', 1),
(2, 1, 'java is', 'fish fry', 'software language', 'programing language', 'web maker', 'optionc', 1),
(2, 2, 'what is vaja', 'bengali', 'kokl', 'khsd', 'kojsgf', 'optiona', 1);
Table ###
--
-- Table structure for table student
CREATE TABLE IF NOT EXISTS `student` (
`stdid` bigint(20) NOT NULL,
`stdname` varchar(40) DEFAULT NULL,
`stdpassword` varchar(40) DEFAULT NULL,
`emailid` varchar(40) DEFAULT NULL,
`contactno` varchar(20) DEFAULT NULL,
`address` varchar(40) DEFAULT NULL,
`city` varchar(40) DEFAULT NULL,
`pincode` varchar(20) DEFAULT NULL,
PRIMARY KEY (`stdid`),
UNIQUE KEY `stdname` (`stdname`),
UNIQUE KEY `emailid` (`emailid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Table structure for table studentquestion
CREATE TABLE IF NOT EXISTS `studentquestion` (
`stdid` bigint(20) NOT NULL DEFAULT '0',
`testid` bigint(20) NOT NULL DEFAULT '0',
`qnid` int(11) NOT NULL DEFAULT '0',
`answered` enum('answered','unanswered','review') DEFAULT NULL,
`stdanswer` enum('optiona','optionb','optionc','optiond') DEFAULT NULL,
PRIMARY KEY (`stdid`,`testid`,`qnid`),
KEY `testid` (`testid`,`qnid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Constraints for table `question`
--
ALTER TABLE `question`
ADD CONSTRAINT `question_ibfk_1` FOREIGN KEY (`testid`) REFERENCES `test` (`testid`);
--
-- Constraints for table `studentquestion`
--
ALTER TABLE `studentquestion`
ADD CONSTRAINT `studentquestion_ibfk_1` FOREIGN KEY (`stdid`) REFERENCES `student` (`stdid`),
ADD CONSTRAINT `studentquestion_ibfk_2` FOREIGN KEY (`testid`, `qnid`) REFERENCES `question` (`testid`, `qnid`);
ERROR MESSAGE
Cannot delete or update a parent row: a foreign key constraint fails (oes.studentquestion, CONSTRAINT studentquestion_ibfk_2 FOREIGN KEY (testid, qnid) REFERENCES question (testid, qnid))
Perhaps it is not the full script you have.
Most probably the data is inserted in wrong order. The error occurs because the table studentquestion already has the data for the testid and qnid fields which is not present is the question master table. You have to reorder your insert-statements so that master tables are populated first and the detail tables after them.

Error 1452 Foreign Key Fails

I am getting a 1452 error from MySQL. Here is the SQL I used to INSERT
INSERT INTO `Quote` (`QTE_id`, `USR_id`, `QTE_total`, `QTE_desc`, `QTE_dateCreated`, `QTE_dateModified`,`QTE_name`, `QTE_status`)
VALUES
(39, 2, NULL, 'desc', '2013-11-19 00:00:00', '2013-11-19 11:22:49', 'test', 'Active');
Cannot add or update a child row: a foreign key constraint fails (`dbNAME`.`Quote`, CONSTRAINT `USR_id1` FOREIGN KEY (`USR_id`) REFERENCES `users` (`USR_id`))
I am positive that the USR_id I am trying to put into the Quote table exists. Any ideas? A lot of the other questions on Stack Overflow did not answer my question.
Here is the Create syntax for the following tables I am trying to insert and relate (generated from Workbench):
CREATE TABLE `Quote` (
`QTE_id` int(11) NOT NULL AUTO_INCREMENT,
`USR_id` int(11) DEFAULT NULL,
`QTE_total` decimal(7,2) DEFAULT NULL,
`QTE_desc` text,
`QTE_dateCreated` timestamp NULL DEFAULT NULL,
`QTE_dateModified` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`QTE_name` varchar(255) DEFAULT NULL,
`QTE_status` varchar(30) DEFAULT NULL,
PRIMARY KEY (`QTE_id`),
KEY `USR_id1` (`USR_id`),
CONSTRAINT `USR_id1` FOREIGN KEY (`USR_id`) REFERENCES `users` (`USR_id`)
) ENGINE=InnoDB AUTO_INCREMENT=39 DEFAULT CHARSET=utf8;
And the User Table:
CREATE TABLE `Users` (
`USR_id` int(11) NOT NULL AUTO_INCREMENT,
`MGR_id` int(11) NOT NULL DEFAULT '0'
`REP_id` int(11) NOT NULL,
`USR_name` varchar(255) NOT NULL,
`USR_login` varchar(255) NOT NULL,
`USR_dateModified` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`USR_dateCreated` datetime NOT NULL,
`USR_role` enum('Salesperson','Manager') DEFAULT NULL,
PRIMARY KEY (`USR_id`,`MGR_id`,`REP_id`),
KEY `MGR_id_idx` (`MGR_id`),
KEY `REP_id_idx` (`REP_id`),
KEY `USR_login` (`USR_login`),
CONSTRAINT `MGR_id` FOREIGN KEY (`MGR_id`) REFERENCES `users` (`USR_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `REP_id` FOREIGN KEY (`REP_id`) REFERENCES `representative` (`REP_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
I had to do a few small changes (change the users to Users, add a ',' at the end of line that defines MGR_id, remove the constraint for REP_id) to make the two CREATEs to work.
Here are the exact CREATEs:
CREATE TABLE `Users` (
`USR_id` int(11) NOT NULL AUTO_INCREMENT,
`MGR_id` int(11) NOT NULL DEFAULT '0',
`REP_id` int(11) NOT NULL,
`USR_name` varchar(255) NOT NULL,
`USR_login` varchar(255) NOT NULL,
`USR_dateModified` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`USR_dateCreated` datetime NOT NULL,
`USR_role` enum('Salesperson','Manager') DEFAULT NULL,
PRIMARY KEY (`USR_id`,`MGR_id`,`REP_id`),
KEY `MGR_id_idx` (`MGR_id`),
KEY `REP_id_idx` (`REP_id`),
KEY `USR_login` (`USR_login`),
CONSTRAINT `MGR_id` FOREIGN KEY (`MGR_id`) REFERENCES `Users` (`USR_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
CREATE TABLE `Quote` (
`QTE_id` int(11) NOT NULL AUTO_INCREMENT,
`USR_id` int(11) DEFAULT NULL,
`QTE_total` decimal(7,2) DEFAULT NULL,
`QTE_desc` text,
`QTE_dateCreated` timestamp NULL DEFAULT NULL,
`QTE_dateModified` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`QTE_name` varchar(255) DEFAULT NULL,
`QTE_status` varchar(30) DEFAULT NULL,
PRIMARY KEY (`QTE_id`),
KEY `USR_id1` (`USR_id`),
CONSTRAINT `USR_id1` FOREIGN KEY (`USR_id`) REFERENCES `Users` (`USR_id`)
) ENGINE=InnoDB AUTO_INCREMENT=39 DEFAULT CHARSET=utf8;
With that in place the following two INSERTs worked:
mysql> INSERT INTO `Users` (`USR_id`, `MGR_id`) VALUES(2, 2);
Query OK, 1 row affected, 4 warnings (0.22 sec)
mysql> INSERT INTO `Quote` (`QTE_id`, `USR_id`, `QTE_total`, `QTE_desc`, `QTE_dateCreated`, `QTE_dateModified`,`QTE_name`, `QTE_status`) VALUES (39, 2, NULL, 'desc', '2013-11-19 00:00:00', '2013-11-19 11:22:49', 'test', 'Active');
Query OK, 1 row affected (0.22 sec)
I hope this helps.