I get the following error when trying to import data via MySQL Workbench:
Preparing...
Importing DataInputs.sql...
Finished executing script
ERROR 1452 (23000) at line 6: Cannot add or update a child row: a foreign key constraint fails (`nsldatabase`.`player`, CONSTRAINT `playsFor` FOREIGN KEY (`player_ID`) REFERENCES `team` (`team_ID`))
Operation failed with exitcode 1
I am creating the database via two different SQL scripts. One creates the tables, and another imports the data. I thought initially that some foreign key wasn't define properly, but it seems like they are all setup properly. Any help would be great. See both files below:
This is the NSLStructure.sql file:
DROP DATABASE IF EXISTS NSLdatabase;
CREATE SCHEMA IF NOT EXISTS NSLdatabase;
USE NSLdatabase;
CREATE TABLE player (
player_ID int NOT NULL,
player_Name text NOT NULL,
player_Position text NOT NULL,
player_Skills int NOT NULL,
team_ID int NOT NULL,
CONSTRAINT playerPK PRIMARY KEY (player_ID)
);
CREATE TABLE history (
history_ID int NOT NULL,
player_ID int NOT NULL,
history_Desc text NOT NULL,
history_sDate text NOT NULL,
history_eDate text NOT NULL,
CONSTRAINT recordPK PRIMARY KEY (history_ID, player_ID)
);
CREATE TABLE field (
field_ID int NOT NULL,
field_Name text NOT NULL,
field_Location text NOT NULL,
CONSTRAINT fieldPK PRIMARY KEY (field_ID)
);
CREATE TABLE team (
team_ID int NOT NULL,
team_Name text NOT NULL,
team_City text NOT NULL,
field_ID int NOT NULL,
captain_ID int NOT NULL,
team_coach text NOT NULL,
CONSTRAINT teamPK PRIMARY KEY (team_ID)
);
CREATE TABLE matches (
matches_ID int NOT NULL,
matches_Date text NOT NULL,
matches_Score text NOT NULL,
matches_Winner text NOT NULL,
field_ID int NOT NULL,
teamHost_ID int NOT NULL,
teamGuest_ID int NOT NULL,
CONSTRAINT matchesPK PRIMARY KEY (matches_ID)
);
CREATE TABLE goal (
goal_ID int NOT NULL,
goal_Time int NOT NULL,
matches_ID int NOT NULL,
player_ID int NOT NULL,
CONSTRAINT goalPK PRIMARY KEY (goal_ID, matches_ID, player_ID)
);
ALTER TABLE team
ADD CONSTRAINT capitanRel FOREIGN KEY (captain_ID)
REFERENCES player (player_ID);
ALTER TABLE team
ADD CONSTRAINT playedOnField FOREIGN KEY (field_ID)
REFERENCES field (field_ID);
ALTER TABLE player
ADD CONSTRAINT playsFor FOREIGN KEY (player_ID)
REFERENCES team (team_ID);
ALTER TABLE history
ADD CONSTRAINT hasRel FOREIGN KEY (player_ID)
REFERENCES player (player_ID);
ALTER TABLE goal
ADD CONSTRAINT scoredBy FOREIGN KEY (player_ID)
REFERENCES player (player_ID);
ALTER TABLE goal
ADD CONSTRAINT scoredIn FOREIGN KEY (matches_ID)
REFERENCES matches (matches_ID);
ALTER TABLE matches
ADD CONSTRAINT playedOn FOREIGN KEY (field_ID)
REFERENCES field (field_ID);
ALTER TABLE matches
ADD CONSTRAINT playedHost FOREIGN KEY (teamHost_ID)
REFERENCES team (team_ID);
ALTER TABLE matches
ADD CONSTRAINT playedGuest FOREIGN KEY (teamGuest_ID)
REFERENCES team (team_ID);
This is the DataInputs.sql file:
USE NSLdatabase;
INSERT INTO player
VALUES
(1, "Paxton Pomykal", "Midfielder", 7.5, 1);
INSERT INTO history
VALUES
(1, 3, "US 20 Squad", "11/27/2003", "12/19/2003");
INSERT INTO field
VALUES
(1, "Dicks Sporting Goods Park", "Commerce City, CO");
INSERT INTO team
VALUES
(2, "Colorado Rapids", "Denver, CO", 1, 3, "Robin Fraser");
INSERT INTO matches
VALUES
(1, "01/08/2019", "0-1", 2, 1, 1, 2);
INSERT INTO goal
VALUES
(1, 32, 1, 19);
You are not inserting the data in the correct sequence. Parent rows need to be created before children rows, so the foreign key constraints are not violated.
So, typically, you need to create rows in team rows before creating rows in player. There may be other dependencies that you need to look into, based on the same logic.
An alternative approach would be to add the foreign key constraints after the data is inserted. However, I would not necessarily recommend that: if your data has invalid relationships, you will not be able to create the foreign keys. It is safer to proceed the other way around, since offending rows are immediately signaled.
Related
I need to create a table with this following relational schema.
The relational schema for this the new table is as follows:
The foreign keys for this new table are as follows:
Transit.{package, departDistributionCentre, departTimestamp}
references Depart.{package, distributionCentre, timestamp}
Transit.{package, arriveDistributionCentre, arriveTimestamp}
references Arrive.{package, distributionCentre, timestamp}
The table that i want to create is named Transit, with a particular column value must be one of this {“Plane”, “Car”, “Truck”}.
This is the code that i create, but apparently, the requirement to answer this question is not allowing me to insert values into table.
CREATE TABLE DeliveryMethod (
MethodCode INT NOT NULL,
Description VARCHAR(50),
PRIMARY KEY (MethodCode)
);
INSERT INTO DeliveryMethod (MethodCode, Description) VALUES (1, "Plane"), (2, "Car"), (3, "Truck");
CREATE TABLE Transit (
package VARCHAR(10) NOT NULL,
departDistributionCentre VARCHAR(100) NOT NULL,
departTimestamp TIMESTAMP NOT NULL,
arriveDistributionCentre VARCHAR(100) NOT NULL,
arriveTimestamp TIMESTAMP NOT NULL,
method INT NOT NULL,
cost INT,
PRIMARY KEY (package, departDistributionCentre, departTimestamp, arriveDistributionCentre, arriveTimestamp),
CONSTRAINT method_fk FOREIGN KEY (method) REFERENCES DeliveryMethod(MethodCode) ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT depart_fk FOREIGN KEY (package, departDistributionCentre, departTimestamp) REFERENCES Depart(package, distributionCentre, timestamp) ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT arrive_fk FOREIGN KEY (package, arriveDistributionCentre, arriveTimestamp) REFERENCES Arrive(package, distributionCentre, timestamp) ON DELETE RESTRICT ON UPDATE CASCADE
);
any of you good people have a lead to solve this without inserting values to a table as reference?
Thanks
Hi I'm not very familiar with MySQL as I have only started using it today and I keep getting this syntax error and am not really sure what the problem is. I have attached a screenshot of the code and also pasted it below with the error in bold.
I'm sorry if this is a silly error that is easily fixed I'm just not sure how to fix it and would be very appreciative of any help.
CREATE TABLE copy (
`code` INT NOT NULL,
isbn CHAR(17) NOT NULL,
duration TINYINT NOT NULL,
CONSTRAINT pkcopy PRIMARY KEY (isbn, `code`),
CONSTRAINT fkcopy FOREIGN KEY (isbn) REFERENCES book (isbn));
CREATE TABLE student (
`no` INT NOT NULL,
`name` VARCHAR(30) NOT NULL,
school CHAR(3) NOT NULL,
embargo BIT NOT NULL,
CONSTRAINT pkstudent PRIMARY KEY (`no`));
CREATE TABLE loan (
`code` INT NOT NULL,
`no` INT NOT NULL,
taken DATE NOT NULL,
due DATE NOT NULL,
`return` DATE NULL,
CONSTRAINT pkloan PRIMARY KEY (taken, `code`, `no`),
CONSTRAINT fkloan FOREIGN KEY (`code`, `no`) REFERENCES copy, student **(**`code`, `no`));
Create the tables first, then use the ALTER TABLE statement to add the foreign keys one by one. You won't be able to call two different tables on the foreign key, so you'll have to use an ID that maps to both. Here is an example to add the foreign keys after the table has been created:
Add a new table named vendors and change the products table to include the vendor id field:
USE dbdemo;
CREATE TABLE vendors(
vdr_id int not null auto_increment primary key,
vdr_name varchar(255)
)ENGINE=InnoDB;
ALTER TABLE products
ADD COLUMN vdr_id int not null AFTER cat_id;
To add a foreign key to the products table, you use the following statement:
ALTER TABLE products
ADD FOREIGN KEY fk_vendor(vdr_id)
REFERENCES vendors(vdr_id)
ON DELETE NO ACTION
ON UPDATE CASCADE;
I'm using an a mySQL db on localhosts. Created table with primary key and another table with foreign key pointing to that one, but when I want to see the results all I geted is "alert" that MySQL returned emty result. Here my tables
CREATE TABLE example_1(
ex1_id int NOT NULL AUTO_INCREMENT,
first_name varchar(50) NULL,
last_name varchar(50) NULL,
CONSTRAINT example_1_pk PRIMARY KEY (ex1_id)
);
CREATE TABLE example_2 (
ex2_id int NOT NULL AUTO_INCREMENT,
acces_lvl int NOT NULL,
CONSTRAINT example_2_pk PRIMARY KEY (ex2_id)
);
CREATE TABLE example_3 (
ex3_id int NOT NULL AUTO_INCREMENT,
first int NOT NULL,
second int NOT NULL,
CONSTRAINT example_3_pk PRIMARY KEY (ex3_id),
FOREIGN KEY (first) REFERENCES example_1(ex1_id),
FOREIGN KEY (second) REFERENCES example_2(ex2_id)
);
Then I add something to db, eg.
INSERT INTO `example_1`(`first_name`, `last_name`) VALUES ('foo', 'bar');
and
INSERT INTO `example_2`(`acces_lvl`) VALUES (2)
then when I try
SELECT * FROM `example_3`
I have nothing, empty results. Shouldn't be there id's from other tables? Am I doing something wrong, or I didn't do something? I'm totally noob in database.
Because you did not insert any data into example_3. Foreign key constraints don't propagate data, they just enforce the data relationship, so when you do insert data into example_3, the values you put in the columns with foreign key constraints have corresponding values in other table.
i got these two succesfull queries:
create table Donors (
donor_id int not null auto_increment primary key,
gender varchar(1) not null,
date_of_birth date not null,
first_name varchar(20) not null,
middle_name varchar(20),
last_name varchar(30) not null,
home_phone tinyint(10),
work_phone tinyint(10),
cell_mobile_phone tinyint(10),
medical_condition text,
other_details text );
and
create table Donors_Medical_Condition (
donor_id int not null,
condition_code int not null,
seriousness text,
primary key(donor_id, condition_code),
foreign key(donor_id) references Donors(donor_id) );
but when i try this one:
create table Medical_Conditions (
condition_code int not null,
condition_name varchar(50) not null,
condition_description text,
other_details text,
primary key(condition_code),
foreign key(condition_code) references Donors_Medical_Condition(condition_code) );
i get "Error Code: 1215, cannot add foreign key constraint"
i dont know what am i doing wrong.
In MySql, a foreign key reference needs to reference to an index (including primary key), where the first part of the index matches the foreign key field. If you create an an index on condition_code or change the primary key st that condition_code is first you should be able to create the index.
To define a foreign key, the referenced parent field must have an index defined on it.
As per documentation on foreign key constraints:
REFERENCES tbl_name (index_col_name,...)
Define an INDEX on condition_code in parent table Donors_Medical_Condition and it should be working.
create table Donors_Medical_Condition (
donor_id int not null,
condition_code int not null,
seriousness text,
KEY ( condition_code ), -- <---- this is newly added index key
primary key(donor_id, condition_code),
foreign key(donor_id) references Donors(donor_id) );
But it seems you defined your tables order and references wrongly.
You should have defined foreign key in Donors_Medical_Condition table but not in Donors_Medical_Conditions table. The latter seems to be a parent.
Modify your script accordingly.
They should be written as:
-- create parent table first ( general practice )
create table Medical_Conditions (
condition_code int not null,
condition_name varchar(50) not null,
condition_description text,
other_details text,
primary key(condition_code)
);
-- child table of Medical_Conditions
create table Donors_Medical_Condition (
donor_id int not null,
condition_code int not null,
seriousness text,
primary key(donor_id, condition_code),
foreign key(donor_id) references Donors(donor_id),
foreign key(condition_code)
references Donors_Medical_Condition(condition_code)
);
Refer to:
MySQL Using FOREIGN KEY Constraints
[CONSTRAINT [symbol]] FOREIGN KEY
[index_name] (index_col_name, ...)
REFERENCES tbl_name (index_col_name,...)
[ON DELETE reference_option]
[ON UPDATE reference_option]
reference_option:
RESTRICT | CASCADE | SET NULL | NO ACTION
A workaround for those who need a quick how-to:
FYI: My issue was NOT caused by the inconsistency of the columns’ data types/sizes, collation or InnoDB storage engine.
How to:
Download a MySQL workbench and use it’s GUI to add foreign key. That’s it!
Why:
The error DOES have something to do with indexes. I learned this from the DML script automatically generated by the MySQL workbench. Which also helped me to rule out all those inconsistency possibilities.It applies to one of the conditions to which the foreign key definition subject. That is: “MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan.” Here is the official statement: http://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html
I did not get the idea of adding an index ON the foreign key column(in the child table), only paid attention to the referenced TO column(in the parent table).
Here is the auto-generated script(PHONE.PERSON_ID did not have index originally):
ALTER TABLE `netctoss`.`phone`
ADD INDEX `personfk_idx` (`PERSON_ID` ASC);
ALTER TABLE `netctoss`.`phone`
ADD CONSTRAINT `personfk`
FOREIGN KEY (`PERSON_ID`)
REFERENCES `netctoss`.`person` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
I think you've got your tables a bit backwards. I'm assuming that Donors_Medical_Condtion links donors and medical conditions, so you want a foreign key for donors and conditions on that table.
UPDATED
Ok, you're also creating your tables in the wrong order. Here's the entire script:
create table Donors (
donor_id int not null auto_increment primary key,
gender varchar(1) not null,
date_of_birth date not null,
first_name varchar(20) not null,
middle_name varchar(20),
last_name varchar(30) not null,
home_phone tinyint(10),
work_phone tinyint(10),
cell_mobile_phone tinyint(10),
medical_condition text,
other_details text );
create table Medical_Conditions (
condition_code int not null,
condition_name varchar(50) not null,
condition_description text,
other_details text,
primary key(condition_code) );
create table Donors_Medical_Condition (
donor_id int not null,
condition_code int not null,
seriousness text,
primary key(donor_id, condition_code),
foreign key(donor_id) references Donors(donor_id),
foreign key(condition_code) references Medical_Conditions(condition_code) );
I got the same issue and as per given answers, I verified all datatype and reference but every time I recreate my tables I get this error. After spending couple of hours I came to know below command which gave me inside of error-
SHOW ENGINE INNODB STATUS;
LATEST FOREIGN KEY ERROR
------------------------
2015-05-16 00:55:24 12af3b000 Error in foreign key constraint of table letmecall/lmc_service_result_ext:
there is no index in referenced table which would contain
the columns as the first columns, or the data types in the
referenced table do not match the ones in table. Constraint:
,
CONSTRAINT "fk_SERVICE_RESULT_EXT_LMC_SERVICE_RESULT1" FOREIGN KEY ("FK_SERVICE_RESULT") REFERENCES "LMC_SERVICE_RESULT" ("SERVICE_RESULT") ON DELETE NO ACTION ON UPDATE NO ACTION
I removed all relation using mysql workbench but still I see same error. After spending few more minutes, I execute below statement to see all constraint available in DB-
select * from information_schema.table_constraints where
constraint_schema = 'XXXXX'
I was wondering that I have removed all relationship using mysql workbench but still that constraint was there. And the reason was that because this constraint was already created in db.
Since it was my test DB So I dropped DB and when I recreate all table along with this table then it worked. So solution was that this constraint must be deleted from DB before creating new tables.
Check that both fields are the same size and if the referenced field is unsigned then the referencing field should also be unsigned.
This is an example of some tables that I'm using.
create TABLE People(
peopleID int not null,
name varchar(40) not null,
primary key (peopleID)
);
create table car(
carID int not null,
peopleID int not null,
primary key (carID),
foreign key (peopleID) references People(peopleID)
);
How do I ensure that when I insert into 'car', the 'peopleID' foreign key exists as a primary key in the table 'People'.
For example, I would want the following statement to throw an error:
INSERT INTO car VALUES (123, 343);
... because 343 doesn't exist in 'PeopleID', as it is empty.
Thanks
This is a bit long for a comment.
You have described what the foreign key constraint does:
For storage engines supporting foreign keys, MySQL rejects any INSERT
or UPDATE operation that attempts to create a foreign key value in a
child table if there is no a matching candidate key value in the
parent table.
The constraint is described here.