Error Code: 1452. Cannot add or update a child row - mysql

I am trying to load data to following tables:
-- -----------------------------------------------------
-- Table `mydb`.`Gener`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`Gener` (
`Movie_Name` VARCHAR(100) NOT NULL ,
`Genres_Type` VARCHAR(100) NULL ,
`Movie_Year` VARCHAR(100) NOT NULL ,
PRIMARY KEY (`Movie_Name`, `Movie_Year`) ,
CONSTRAINT `fk_Gener_Movie1`
FOREIGN KEY (`Movie_Name` , `Movie_Year` )
REFERENCES `mydb`.`Movie` (`Name` , `Year` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
-- -----------------------------------------------------
-- Table `mydb`.`Movie`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`Movie` (
`Name` VARCHAR(100) NULL ,
`Lenght` INT(20) NULL ,
`Year` VARCHAR(100) NOT NULL ,
`id` INT(5) NOT NULL AUTO_INCREMENT ,
PRIMARY KEY (`id`, `Name`, `Year`) )
-- -----------------------------------------------------
-- Table `mydb`.`tempGener`
-- -----------------------------------------------------
CREATE TABLE `mydb`.`tempGener' (
`mGName` VARCHAR(100),
`mGType` VARCHAR(100),
`mGYear` VARCHAR(100)
)
I successfully uploading data to following two tables.
tempGener,
movie.
Now I trying to load data to my Gener table by using following command,
INSERT INTO gener (Movie_Name, Genres_Type, Movie_Year)
(SELECT movie.Name, tempgener.mGType , movie.Year
FROM tempgener, movie)
But I receive following errors:
Error Code: 1452. Cannot add or update a child row: a foreign key
constraint fails (mydb3.gener, CONSTRAINT fk_Gener_Movie1
FOREIGN KEY (Movie_Name, Movie_Year) REFERENCES mydb.movie
(Name, Year) ON DELETE NO ACTION ON UPDATE NO ACTION)

I solve my problem, the problem was, I was missing WHERE statement.
Thanks for every body giving me fast response.

Related

INSERT ON DUPLICATE KEY with INNER JOIN

Given t.id, a.id, t1.name and t2.name, how do I add or update t1_has_t2.data?
I can update it if there is currently a record.
UPDATE t1_has_t2
INNER JOIN t1 ON t1.id=t1_has_t2.t1_id
INNER JOIN t2 ON t2.id=t1_has_t2.t2_id
SET t1_has_t2.data=123
WHERE t1.name="foo" AND t1.t_id=333 AND t2.name="bar" AND t2.t_id=333;
How can I insert it if a record currently doesn't exist?
EDIT. Would it be something like the following? Seems a waste to include t in the JOIN.
INSERT INTO t1_has_t2(t1_id,t2_id,data)
SELECT t1.id, t2.id, 123
FROM t
INNER JOIN t1 ON t1.t_id=t.id
INNER JOIN t2 ON t2.t_id=t.id
WHERE t1.name="foo" AND t1.t_id=333 AND t2.name="bar" AND t2.t_id=333
ON DUPLICATE KEY SET t1_has_t2.data=123;
EDIT2. Ah, maybe I get it now. I just JOIN t1 and t2 to each other through their shared t.id?
INSERT INTO t1_has_t2(t1_id,t2_id,data)
SELECT t1.id, t2.id, 123
FROM t1
INNER JOIN t2 ON t2.t_id=t1.t_id
WHERE t1.name="foo" AND t1.t_id=333 AND t2.name="bar" AND t2.t_id=333
ON DUPLICATE KEY UPDATE t1_has_t2.data=123;
-- MySQL Script generated by MySQL Workbench
-- 08/08/16 07:40:04
-- Model: New Model Version: 1.0
SET #OLD_UNIQUE_CHECKS=##UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET #OLD_FOREIGN_KEY_CHECKS=##FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET #OLD_SQL_MODE=##SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema mydb
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `mydb` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;
USE `mydb` ;
-- -----------------------------------------------------
-- Table `mydb`.`accounts`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`accounts` (
`id` INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`t`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`t` (
`id` INT NOT NULL AUTO_INCREMENT,
`accounts_id` INT NOT NULL,
PRIMARY KEY (`id`, `accounts_id`),
INDEX `fk_t_accounts_idx` (`accounts_id` ASC),
CONSTRAINT `fk_t_accounts`
FOREIGN KEY (`accounts_id`)
REFERENCES `mydb`.`accounts` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`t1`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`t1` (
`id` INT NOT NULL AUTO_INCREMENT,
`t_id` INT NOT NULL,
`t_accounts_id` INT NOT NULL,
`name` VARCHAR(45) NULL,
PRIMARY KEY (`id`),
INDEX `fk_t1_t1_idx` (`t_id` ASC, `t_accounts_id` ASC),
UNIQUE INDEX `un1` (`t_id` ASC, `name` ASC),
CONSTRAINT `fk_t1_t1`
FOREIGN KEY (`t_id` , `t_accounts_id`)
REFERENCES `mydb`.`t` (`id` , `accounts_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`t2`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`t2` (
`id` INT NOT NULL AUTO_INCREMENT,
`t_id` INT NOT NULL,
`t_accounts_id` INT NOT NULL,
`name` VARCHAR(45) NULL,
PRIMARY KEY (`id`),
INDEX `fk_t2_t1_idx` (`t_id` ASC, `t_accounts_id` ASC),
UNIQUE INDEX `un2` (`t_id` ASC, `name` ASC),
CONSTRAINT `fk_t2_t1`
FOREIGN KEY (`t_id` , `t_accounts_id`)
REFERENCES `mydb`.`t` (`id` , `accounts_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`t1_has_t2`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`t1_has_t2` (
`t1_id` INT NOT NULL,
`t2_id` INT NOT NULL,
`data` VARCHAR(45) NULL,
PRIMARY KEY (`t1_id`, `t2_id`),
INDEX `fk_t1_has_t2_t21_idx` (`t2_id` ASC),
INDEX `fk_t1_has_t2_t11_idx` (`t1_id` ASC),
CONSTRAINT `fk_t1_has_t2_t11`
FOREIGN KEY (`t1_id`)
REFERENCES `mydb`.`t1` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_t1_has_t2_t21`
FOREIGN KEY (`t2_id`)
REFERENCES `mydb`.`t2` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SET SQL_MODE=#OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=#OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=#OLD_UNIQUE_CHECKS;
Works fine if I understand what you want with Insert on Duplicate Key Update (IODKU).
Data Load:
insert accounts(id) values (NULL); -- id = 1
insert t(accounts_id) values (1); -- id = 1
insert t1(t_id,t_accounts_id,name) values (1,1,'n1'); -- id=1
insert t1(t_id,t_accounts_id,name) values (1,1,'n2'); -- id=2
insert t2(t_id,t_accounts_id,name) values (1,1,'n1'); -- id=1
insert t2(t_id,t_accounts_id,name) values (1,1,'n2'); -- id=2
insert t1_has_t2(t1_id,t2_id,data) values(1,1,'one_one'); -- success
insert t1_has_t2(t1_id,t2_id,data) values(1,77,'x'); -- Error 1452 as expected
insert t1_has_t2(t1_id,t2_id,data) values(77,1,'x'); -- Error 1452 as expected
insert t1_has_t2(t1_id,t2_id,data) values(1,2,'one_two'); -- success
insert t1_has_t2(t1_id,t2_id,data) values(2,1,'two_one'); -- success
insert t1_has_t2(t1_id,t2_id,data) values(2,2,'two_two'); -- success
Your Query:
UPDATE t1_has_t2
INNER JOIN t1 ON t1.id=t1_has_t2.t1_id
INNER JOIN t2 ON t2.id=t1_has_t2.t2_id
SET t1_has_t2.data='I am a string'
WHERE t1.name="n1" AND t1.t_id=1 AND t2.name="n1" AND t2.t_id=1;
IODKU:
insert t1_has_t2(t1_id,t2_id,data) values(2,2,'two_two_version002')
on duplicate key update data='anchovies';
See results:
select * from t1_has_t2;
+-------+-------+---------------+
| t1_id | t2_id | data |
+-------+-------+---------------+
| 1 | 1 | I am a string |
| 1 | 2 | one_two |
| 2 | 1 | two_one |
| 2 | 2 | anchovies |
+-------+-------+---------------+
You can also look into
insert ignore t1_has_t2(t1_id,t2_id,data) [something];
Which succeeds or fails silently by design.

Reserve/Assign a new row in another table with each row added in one

I'll like to find out if it's possible to do the following:
after insertion of data into table a, a row will be created automatically in table b and the Note_Id (its primary key) will be stored in one of the attributes (which is a foreign key that references to the primary key in table b) in table a.
CREATE TABLE table_a ( D_Id int(5) NOT NULL AUTO_INCREMENT,
User_Id int(8) not null,
Note_Id int(5) not null, -- this is the foreign key that points to table b
PRIMARY KEY (D_Id) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE table_b ( Note_Id int(5) NOT NULL AUTO_INCREMENT,
Note_Description varchar(50) null,
PRIMARY KEY (Note_Id) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Thanks!
delimiter $$
CREATE TRIGGER ins_Document
AFTER INSERT ON TABLE_A FOR EACH ROW
BEGIN
set #notenum=(Select max(Note_Id) from TABLE_B);
if(#notenum=0) then begin new.Note_Id=1;
end;
else
new.Note_Id=#notenum+1;
end if;
INSERT INTO TABLE_B (Note_Id) VALUES (NEW.Note_Id);
END$$
delimiter ;
Have a look into triggers: Create Trigger
Here you can react on events like inserts into a table and define respective actions for that.

SQL error: 1364 Field 'XXXX' doesn't have a default value

So I have, table courses:
CREATE TABLE IF NOT EXISTS `AppDziennik`.`courses` (
`id_course` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(80) NOT NULL ,
`teachers_id_teacher` INT NOT NULL ,
`end_date` DATE NULL ,
`about` VARCHAR(255) NULL ,
`start_date` DATE NULL ,
PRIMARY KEY (`id_course`) ,
UNIQUE INDEX `id_course_UNIQUE` (`id_course` ASC) ,
CONSTRAINT `fk_courses_teachers1`
FOREIGN KEY (`teachers_id_teacher` )
REFERENCES `AppDziennik`.`teachers` (`id_teacher` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
and second table
CREATE TABLE IF NOT EXISTS `AppDziennik`.`teachers` (
`id_teacher` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(45) NOT NULL ,
`surname` VARCHAR(45) NOT NULL ,
`about` VARCHAR(255) NULL ,
`id_class` INT NULL ,
`rank` VARCHAR(45) NULL ,
`logins_id_login` INT NOT NULL ,
PRIMARY KEY (`id_teacher`) ,
INDEX `fk_teachers_classes1_idx` (`id_class` ASC) ,
INDEX `fk_teachers_logins1_idx` (`logins_id_login` ASC) ,
CONSTRAINT `fk_teachers_classes1`
FOREIGN KEY (`id_class` )
REFERENCES `AppDziennik`.`classes` (`id_class` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_teachers_logins1`
FOREIGN KEY (`logins_id_login` )
REFERENCES `AppDziennik`.`logins` (`id_login` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
When I make that insert
insert into appdziennik.courses
(name, id_teacher, about, start_date, end_date)
values ("Math",'7',"Math",'2013-08-01','2014-06-29');
I get that error:
Error Code: 1364. Field 'teachers_id_teacher' doesn't have a default
value
Where I made mistake? How i could fix it.
If you're sending an INSERT to table courses, there is no field id_teacher (you want teachers_id_teacher). Since you're using a foreign key, that key must exist in table teachers before you INSERT a record into table courses. Also, you should only be using backticks (`) and single quotes (') in all your statements.
you are trying to insert into the courses table for the column id_teacher a value but your not inserting a value for the column teachers_id_teacher. so I would propose to make the statement as followed:
insert into appdziennik.courses (name, teachers_id_teacher, about, start_date, end_date) values ("Math",'7',"Math",'2013-08-01','2014-06-29');
Sarajog

How to Add integer column to an String column in MySQl 5.0

I Want to add an Integer Column to a String that's because i need to generate a varchar variable with a numeric part that automatically increments. For example, P000001,P000002...
In order to do that what i am doing while creation of table i have taken an int field ID which auto_increments and i am Concatenating P with 00000 and the ID value
The Table i have created is :
CREATE TABLE tblAcceptTest(
ID int AUTO_INCREMENT NOT NULL primary key,
PatientID as CONCAT('P' , CONCAT('000000',CAST(ID as char)))
);
It Shows me the error from as keyword.
Please help
MySQL's documentation (http://dev.mysql.com/doc/refman/5.1/en/create-table.html) says, "the default value must be a constant; it cannot be a function or an expression." Why don't you just get the PatientID value afterward as part of the SELECT:
SELECT CONCAT('P', LPAD(ID, 6, 0)) AS PatientID FROM tblAcceptTest;
It looks like you want six digits after the "P", so try this for your expression:
CONCAT('P', LPAD(ID, 6, '0'))
Mysql has little support for computed columns.
Patient ID from your specification could be a char(7)
CREATE TABLE tblAcceptTest(
ID int AUTO_INCREMENT NOT NULL primary key,
PatientID char(7)
);
Then create some triggers. Note that the following insert trigger will cause issues with high concurrency servers.
DELIMITER |
CREATE TRIGGER tblAcceptTest_insert BEFORE INSERT ON tblAcceptTest
FOR EACH ROW BEGIN
DECLARE next_id INT;
SET next_id = (SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='tblAcceptTest');
SET NEW.PatientID = CONCAT('P' , RIGHT(CONCAT('000000',next_id),6)) ;
END;
|
CREATE TRIGGER tblAcceptTest_update BEFORE UPDATE ON tblAcceptTest
FOR EACH ROW BEGIN
SET NEW.PatientID = CONCAT('P' , RIGHT(CONCAT('000000',NEW.ID),6)) ;
END;
|
DELIMITER ;
You use relationships and views to achieve the same result.
CREATE TABLE `patient` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`patient` varchar(60) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `accepted_test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`patient_id` int(11) NOT NULL,
`accepted` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `patient_id` (`patient_id`),
CONSTRAINT `accepted_test_ibfk_1` FOREIGN KEY (`patient_id`) REFERENCES `patient` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
create or replace view accepted_test_veiw as
select CONCAT('P' , RIGHT(CONCAT('000000',patient_id),6)) patient_key
, accepted
, id accepted_test_id
, patient_id
from accepted_test ;
select * from `accepted_test_veiw`

MySQL - How to create a child record under table2 whenever table1 is having a new record using MySQL workbench?

Trigger actually. But how do i make this in mysql-workbench. So that anytime i have any new records in table1 it creates a new record referencing table1.id to table2.parentid ?
--- [OK] --- This is created
CREATE TABLE IF NOT EXISTS `test`.`table1` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(45) NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB
--- [FAIL] --- #1005 - Can't create table 'test.table2' (errno: 150)
CREATE TABLE IF NOT EXISTS `test`.`table2` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT ,
`parentid` VARCHAR(45) NULL ,
`table1_id` BIGINT(20) NOT NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_table2_table1` (`parentid` ASC) ,
CONSTRAINT `fk_table2_table1`
FOREIGN KEY (`parentid` )
REFERENCES `test`.`table1` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
Follow up:
1) Mysql workbench do not offer that
2) Click the table1 > click the triggers tab bottom > write
-- trigger module initiate
DELIMITER $$
CREATE TRIGGER triggertest1 BEFORE INSERT ON table1
FOR EACH ROW BEGIN
INSERT INTO table2 SET parentid = NEW.id;
END;
$$
DELIMITER ; --- return to normal
Thats because you have different datatype of id column in your child table change it to BIGINT(20)