Error 1452 MySQL Load Infile (but correct data) - mysql

I'm trying to load data from a .txt using LOAD DATA INFILE, the problem is that i get error 1452, but the foreign keys referred are present in my DB. Also other LOAD DATA are working, just can't solve this and 1 other load.
I've checked the referred data, and are present in DB before i load. Also the columns are of the same type. I tried reinstalling MySQL still not working (but a friend of mine using the same code/.txt can load the data). I can load the .txt if it consists of a single line, but when adding a second one i got the error.
-- The table referred:
CREATE TABLE Categoria (
Nome VARCHAR(50) NOT NULL,
Immagine MEDIUMBLOB,
PRIMARY KEY (Nome));
-- The table with FK:
CREATE TABLE Sottocategoria_Di (
Categoria1 VARCHAR(50) NOT NULL,
Categoria2 VARCHAR(50) NOT NULL,
PRIMARY KEY (Categoria1, Categoria2),
FOREIGN KEY (Categoria1) REFERENCES Categoria(Nome) ON DELETE NO ACTION,
FOREIGN KEY (Categoria2) REFERENCES Categoria(Nome) ON DELETE CASCADE);
INSERT INTO Categoria VALUES ('Chitarra', NULL);
INSERT INTO Categoria VALUES ('Chitarra Acustica', NULL);
INSERT INTO Categoria VALUES ('Chitarra Classica', NULL);
LOAD DATA INFILE "C:/ProgramData/MySQL/MySQL Server
8.0/Uploads/MusicShop/Sottocategoria.txt" INTO TABLE
Music.Sottocategoria_Di
CHARACTER SET latin1
FIELDS TERMINATED BY '|'
ENCLOSED BY ''
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(Categoria1,Categoria2);
-- Sottocategoria.txt
Categoria1,Categoria2
Chitarra Classica|Chitarra
Chitarra Acustica|Chitarra
A friend of mine reinstalled MySQL and using the same exact script/.txt can load the file but i still can't.
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (music.sottocategoria_di, CONSTRAINT sottocategoria_di_ibfk_2 FOREIGN KEY (Categoria2) REFERENCES categoria (Nome) ON DELETE CASCADE)

The problem was using lines terminated by '\n', switched to '\r\n' and it worked! Still don't know why it works for other files .txt i'm using (same OS Windows)

Related

AUTO_INCREMENT Indexing Duplicate Entry

I am attempting to load data from a csv file into a MySQL database using the LOAD DATA command.
My csv is structured like:
Index
Name
...
0
blah
1
blahbla
...
But when trying to read my data using
CREATE TABLE data (
id INT NOT NULL AUTO_INCREMENT,
KernelName VARCHAR(255) NOT NULL,
...,
primary key (id)
);
USE myDatabase;
LOAD DATA INFILE '/filepath/myFile.csv'
INTO TABLE myTable
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS;
I receive the error ERROR 1062 (23000): Duplicate entry '1' for key 'myTable.PRIMARY'
I suspect this is happening because the AUTO_INCREMENT is creating a MySQL table where the id starts at 1 instead of the 0 that I'm reading. Causing the duplicate entry error.
New to MySQL and don't care if indexing starts at 0 or 1, just not sure what the easiest fix would be. Should I skip the index row? Change auto_increment to start at 0?
Update
I was able to fix this issue by omitting the AUTO_INCREMENT in my initial CREATE TABLE command. Then after importing data, I used ALTER TABLE table MODIFY id INTEGER NOT NULL AUTO_INCREMENT; to restore auto increment functionality.
Thanks to everyone who helped with this in the comments!

SQL can insert separately but cannot load as file with foreign key

I am new to the database and am following tutorials and doing experiments. So my apology if that question turned out to be stupid.
I set up a table like that:
CREATE TABLE if not exists SAMPLE(
chara varchar(15) not null,
Num char(9),
secNum char(9),
primary key (Num),
foreign key (secNum) references sample(Num)
) engine=innodb;
If I insert entries one by one:
insert into SAMPLE(chara, Num) values ("A", "111");
insert into SAMPLE(chara, Num, secNum) values ("B", "222", "111");
insert into SAMPLE(chara, Num) values ("C", "333");
It works fine. But if I load the following data with load data infile ".../SAMPLE.txt" into table SAMPLE;:
A 111 \N
B 222 111
C 333 \N
I got an error saying:
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`company`.`sample`, CONSTRAINT `sample_ibfk_1` FOREIGN KEY (`secNum`) REFERENCES `sample` (`Num`)) 0.000 sec
I could guess it has something to do with breaking the referential integrity, but I don't know what. And I also don't know why it works with serval inserts but not with the load. Could anyone help me to understand what went wrong and how can I get rid of it? Thanks.
when you separately inserts rows one by one, for the second insert already sees 111 row and it doesn't violate the FK
but when you are loading a file it tries to insert all rows in one batch ( transaction) , so row 111 doesn't exists just yet.

MySQL Cannot add or update a child row

I have two tables: tblACTypeCharacteristics and tblAircrafts.
tblACTypeCharacteristics definition:
create table if not exists tblACTypeCharacteristics(
idAC_type varchar(255) not null,
numPassengers int,
primary key(idAC_type));
tblAircrafts definition:
create table if not exists tblAircrafts(
idAC int not null auto_increment,
txtAC_tag varchar(255) not null,
txtAC_type varchar(255) not null,
primary key(idAC, txtAC_tag));
In addition, I have added an foreign key like followed:
alter table tblaircrafts add foreign key(txtAC_type)
references tblactypecharacteristics(idAC_type);
In tblACTypeCharacteristics, the maximum number of passengers is defined for each type of aircraft.
In tblAircraft are all aircrafts available listed.
I am able to insert a new aircraft by typing for example:
insert into tblaircrafts (txtAC_tag, txtAC_type) values ('OE-LDA','A319-112');
But as there are loads of aircrafts around, I dont want to add each one by hand.
I want to import them by a csv file (I do have a list of a few aircrafts).
And I Import it as followed:
load data local infile 'C:\\Users\\t_lichtenberger\\Desktop\\tblAircrafts.csv'
into table tblaircrafts
character set utf8
fields terminated by ';'
lines terminated by '\n'
ignore 1 lines;
But as I want to Import the .csv file into the tblaircraft table, I get the following error:
15:08:37 alter table tblaircrafts add foreign key(txtAC_type) references tblactypecharacteristics(idAC_type) Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`pilotproject`.`#sql-11d0_2da`, CONSTRAINT `#sql-11d0_2da_ibfk_1` FOREIGN KEY (`txtAC_type`) REFERENCES `tblactypecharacteristics` (`idAC_type`)) 0.641 sec
and I cannot explain why. The number of columns are the same and the datatypes of the columns are the same. And I have double-checked the csv for AC_types which arent in the tblACTypeCharacteristic tables and it should be good..
the first few rows of the csv file look like followed:
Any suggestions why the error still occurs?
Thank you so much in advance!
I finally got the solution. I just disabled the foreign key checks by executing
SET foreign_key_checks = 0;
before setting the foreign keys and it worked! I was able to add the csv records afterwards.

Google Cloud SQL mysql_query Cannot add or update a child row

I'm trying to add records into the follow tables using sql on Google Cloud SQL.
CREATE DATABASE IF NOT EXISTS phunter_spark;
USE phunter_spark;
DROP TABLE IF EXISTS Vote;
DROP TABLE IF EXISTS Product;
CREATE TABLE IF NOT EXISTS Product
(
id varchar(255),
name varchar(255),
PRIMARY KEY (id)
);
CREATE TABLE IF NOT EXISTS Vote
(
userId varchar(255),
prodId varchar(255),
rating int,
PRIMARY KEY(prodId, userId),
FOREIGN KEY (prodId)
REFERENCES Product(id)
);
When uploading the Product table it works perfectly fine. Example Product CSV data is:
57243,We Are Heroes
57242,Tesla Model 3
57239,Captain Strike
57229,Gmail Mic Drop
57223,Sponge Club
However it throws an error when trying to upload Votes. Example Vote CSV data is :
129455,57119,1
105600,57245,1
105600,57246,1
139608,54933,1
129455,57242,1
7926,57242,1
I'm 100% sure ever prodId in the Vote CSV data is contained as an object in the Product SQL database. not quite sure what I'm missing... also relatively new to mysql databases
The error being thrown is as follows:
mysql_query Cannot add or update a child row: a foreign key constraint
fails (`phunter_spark`.`Vote`, CONSTRAINT `Vote_ibfk_1` FOREIGN KEY
(`prodId`) REFERENCES `Product` (`id`)) (LOAD DATA INFILE
'gs://dateless-votes-tenk.csv' INTO TABLE `Vote`
CHARACTER SET 'utf8' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' ESCAPED BY '"')
Your prod ID column in vote table references ID in product table.
FOREIGN KEY (prodId)
REFERENCES Product(id)
This means that any value inserted in prod id column of vote table should be present in id column in Product table.
http://www.w3schools.com/sql/sql_foreignkey.asp
57119,57245 etc in your second csv file may not have reference in the id column of Product table.

MySQL Error 1452 - can't insert data

I am inserting some data into the following MySQL tables:
CREATE TABLE genotype
(
Genotype VARCHAR(20),
Fitness FLOAT NULL,
Tally INT NULL,
PRIMARY KEY (Genotype)
)ENGINE=InnoDB;
CREATE TABLE gene
(
Gene VARCHAR(20),
E FLOAT NOT NULL,
Q2 FLOAT NOT NULL,
PRIMARY KEY (Gene)
)ENGINE=InnoDB;
CREATE TABLE genotypegene
(
Genotype VARCHAR(20),
Gene VARCHAR(20),
FOREIGN KEY (Genotype) REFERENCES genotype(Genotype),
FOREIGN KEY (Gene) REFERENCES gene(Gene)
)ENGINE=InnoDB;
I inserted the data into genotype/gene first, but get the following error when trying to insert into genotypegene:
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`populationdb`.`genotypegene`, CONSTRAINT `genotypegene_ibfk_2` FOREIGN KEY (`Gene`) REFERENCES `gene` (`Gene`))
The data I'm inserting is into this table is:
Genotype1,Gene1
Genotype1,Gene2
Genotype1,Gene3
Genotype1,Gene4
There is one copy of Genotype1 in the genotype table, the idea being that each genotype can contain many genes, but each gene can exist in multiple genotypes (at the moment, there is only 1 genotype, but later I will insert more). I read here that I could turn off Foreign Key Checks, but I am reluctant to do so without knowing the reason for this error. Is this because there is only one copy of Genotype1 in the genotype table? (I have checked that Genotype1, Gene1 etc. are in the same format/spelling in their primary key tables).
Just in case, here is the code I am using to insert the data:
mysql> LOAD DATA LOCAL INFILE 'C:\\.....genotypegene.csv'
-> INTO TABLE genotypegene
-> FIELDS TERMINATED BY ','
-> (Genotype, Gene);
Thanks
One approach to find out what is causing this would be to do the following:
Disable Foreign Keys
SET FOREIGN_KEY_CHECKS = 0;
Load The Data
Do this using your command:
mysql> LOAD DATA LOCAL INFILE 'C:\\.....genotypegene.csv'
-> INTO TABLE genotypegene
-> FIELDS TERMINATED BY ','
-> (Genotype, Gene);
Find Orphaned Data
select gtg.* from genotypegene gtg
where (gtg.Gene not in (select g.Gene from gene g)
or gtg.Genotype not in (select gt.Genotype from genotype gt));
This should give you a list of those rows that are causing your FK constraint violation.
Fix The Orphaned Data
Update them? Delete them? Fix them in the CSV? Insert parent row into Gene table? Do whatever is appropriate.
Enable FK Checks
SET FOREIGN_KEY_CHECKS = 1;
If nothing else this should give you a clue as to why your are getting the FK constraint violation error.
Good luck!
This error sometimes appears when the separator between fields coincides with some value that the field has. Example: If the separator is the comma (,). Possibly some field has this comma and believes it is a field change. Check these cases.