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.
Related
I'm creating tables in MariaDB 10.6 database for TPC-H benchmark.
CREATE TABLE works ok, but adding FOREIGN KEY fails.
I tried following mariadbtutorial and documentation but this doesn't work too.
I suspect:
syntax of FOREIGN KEY is wrong
Wrong datatype in column that reference foreign key.
column refering to foreign key should be index
there's something wrong with data generated by dbgen from TPC-H benchmark.
The errors that occured:
warning 150: alter table bazatest2.nation with foreign key (N_REGIONKEY) constraint failed. field type or character set for column 'N_REGIONKEY' does not match referenced column 'R_REGIONKEY'.
Tried changing BIGINT NOT NULL to BIGINT UNSIGNED NOT NULL
but different error occurs:
error 1452 when i tried adding UNSIGNED to BIGINT in column that should refer to foreign key.
Part of file containing creates:
DROP TABLE IF EXISTS NATION CASCADE;
CREATE TABLE NATION (
N_NATIONKEY SERIAL PRIMARY KEY,
N_NAME CHAR(25),
N_REGIONKEY BIGINT UNSIGNED NOT NULL, -- references R_REGIONKEY
N_COMMENT VARCHAR(152)
);
DROP TABLE IF EXISTS REGION CASCADE;
CREATE TABLE REGION (
R_REGIONKEY SERIAL PRIMARY KEY,
R_NAME CHAR(25),
R_COMMENT VARCHAR(152)
);
Part of file with foreign key constraints:
ALTER TABLE NATION ADD CONSTRAINT FOREIGN KEY (N_REGIONKEY) REFERENCES REGION(R_REGIONKEY);
I tried solving this by changing syntax of alter table add constraint foreign key and searching for solutions all yesterday and haven't found solution.
Most likely is that column referencing to foreign key should be index, or multiple errors,
but I don't know what should i change in my code.
Thanks for all answers,
I added UNSIGNED to BIGINT, but it wasn't main source of my problem.
The problem was that I imported data from file where primary key values started at 0.
Here I found that in MariaDB/MySQL if 0 is given for primary key, it will automatically assign first value. It changed
0, 1, 2 to 1, 1, 2 and error occured.
There are two options:
changing settings of dbgen (program generating data for TPC-H benchmark).
Possible options are: INFORMIX, DB2, TDAT (Teradata), SQLSERVER, SYBASE, ORACLE, VECTORWISE. Options stand for database syntax, by there is no MYSQL option.
dbgen creates '|' separated file (.tbl) with records for this tables.
I used ORACLE and it generated file with primary keys starting at 0.
You can comment if you know which option would be most similar to MySQL syntax and contain keys starting at 0.
Or is there any automatic software which will add 1 to primary keys in this file. Although NATION and REGION tables are not so big (20, 5), some other tables (which I removed from this question for clarity) will have over 100 000 records.
syntax is wrong, use this
ALTER TABLE NATION ADD CONSTRAINT NATION_FK FOREIGN KEY (N_REGIONKEY) REFERENCES REGION(R_REGIONKEY);
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.
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.
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.
I have a table named "label" with 2 columns:
_LABEL_ID (varchar)
_LENGTH (varchar)
This table already has data in it!
And I have several other Tables "a", "b", "c", etc.
these tables have the column _LABEL_ID (varchar). These table are not empty
On delete of any row from tables a, b, c, ...etc., then delete its label from the "label" table. I tried to add foreign key to "label" referenced to table "a" for doing this (just to test it), but getting the same error like in this question:
can't add foreign key in mysql?
In my case I have InnoDB engine for all tables, unique names FK's, same data types.
Now I exported label rows, then emptied the label table, adding foreign key to it referenced to "a" table works just fine. If i import the rows again to the label table, I get the same error which I got when try to add foreign key.
the rows in label table belong to different tables (a, b, c, ..etc). is this the cause of the error?
i do this using MySQL Workbench
EDIT: the real SQL Statement and the Error Message:
ALTER TABLE `cal_view_db`.`dbo_pub_label`
ADD CONSTRAINT `fk_dbo_pub_label_treenode`
FOREIGN KEY (`_LABEL_ID` )
REFERENCES `cal_view_db`.`dbo_system_treenode` (`_NAME_ID` )
ON DELETE CASCADE
ON UPDATE NO ACTION
, ADD INDEX `fk_dbo_pub_label_treenode_idx` (`_LABEL_ID` ASC) ;
Error Message:
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails (`cal_view_db`.`#sql-10cc_4a`, CONSTRAINT `fk_dbo_pub_label_treenode` FOREIGN KEY (`_LABEL_ID`) REFERENCES `dbo_system_treenode` (`_NAME_ID`) ON DELETE CASCADE ON UPDATE NO ACTION)
SQL Statement:
ALTER TABLE `cal_view_db`.`dbo_pub_label`
ADD CONSTRAINT `fk_dbo_pub_label_treenode`
FOREIGN KEY (`_LABEL_ID` )
REFERENCES `cal_view_db`.`dbo_system_treenode` (`_NAME_ID` )
ON DELETE CASCADE
ON UPDATE NO ACTION
, ADD INDEX `fk_dbo_pub_label_treenode_idx` (`_LABEL_ID` ASC)
ERROR: Error when running failback script. Details follow.
ERROR 1046: No database selected
SQL Statement:
CREATE TABLE `dbo_pub_label` (
`_LABEL_ID` varchar(45) NOT NULL,
`_LENGTH` varchar(45) DEFAULT NULL,
PRIMARY KEY (`_LABEL_ID`),
KEY `fk_dbo_pub_label_1_idx` (`_LABEL_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
many thanks
p.s: sorry for my bad english!
Yes, it does seem that your problem is that the data in label belongs to multiple tables.
If I am not mistaken then a FK tells the DB to check in the referenced table for every value in the FK Table.
Here, you have labels from a and b and c and d. When the DB goes to verify the FK it will not find the data in label that corresponds to the data in b,c,d,etc. It will only find the ones that are in a.
This is why your error comes up both when you try and create the table and when you try to reload the data to the table. All records in a FK column must have a match in the referenced table. (Here that is label -> FK -> a)