is it possible to have a foreign key with two reference tables?
here's the script and we're having a problem inserting into this table
CREATE TABLE Class(
idNumber varchar(30) not null,
day varchar(10) not null,
time varchar(20) not null,
foreign key(idNumber) REFERENCES ThesisMember(idNumber),
foreign key(idNumber) REFERENCES Faculty(idNumber),
PRIMARY KEY(idNumber,day,time)
);
CONSTRAINT `class_ibfk_1`
FOREIGN KEY (`idNumber`) REFERENCES `thesismember` (`idNumber`))
SQL Statement:
INSERT INTO `thesis`.`class`
(`idNumber`, `day`, `time`) VALUES ('9990', 'F', '0940-1110')
the Faculty table has the "9990" idNumber.
The FK constraint requires that every instance of the field 'idNumber' occur in ALL referenced tables. You state that only one of the referenced tables has the value to be inserted, so of course an error occurs on the INSERT attempt.
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
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.
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.
im new on mysql workbench, and i tried so many things to put my script working but i simply cant... Ive got these tables:
CREATE TABLE Utilizador (email varchar(40) not null, nome varchar(50)
not null, dataNascimento date, profissao varchar(50) not null,
reputacao double(3,2) unsigned not null, constraint pk_Utilizador
primary key(email))
This is the first table created!
CREATE TABLE POI (email varchar(40) not null, designacaoPOI
varchar(10) not null, coordenadaX int, coordenadaY int,
descricaoPOI varchar(200), constraint pk_POI primary key(email,
designacaoPOI), constraint fk_POI foreign key(email) references
Utilizador(email) on delete cascade)
This is the second table created!
CREATE TABLE Utilizador_POI (email varchar(40) not null, designacaoPOI
varchar(10) not null, constraint pk_Utilizador_POI primary key(email,
designacaoPOI), constraint fk1_Utilizador_POI foreign key(email)
references Utilizador(email) on delete cascade, constraint
fk2_Utilizador_POI foreign key(designacaoPOI) references
POI(designacaoPOI) on delete cascade)
This table gives me the error: Error Code: 1215. Cannot add foreign key constraint
I did some tests and im almost sure that the problem is in the foreign key "designacaoPOI". The other FK ("email") dont give me any error, so maybe the problem is in the Table POI?
Thanks in advanced!
The problem here is twofold:
1/ Use IDs for PRIMARY KEYs
You should be using IDs for primary keys rather than VARCHARs or anything that has any real-world "business meaning". If you want the email to be unique within the Utilizador table, the combination of email and designacaoPOI to be unique in the POI table, and the same combination (email and designacaoPOI) to be unique in Utilizador_POI, you should be using UNIQUE KEY constraints rather than PRIMARY KEY constraints.
2/ You cannot DELETE CASCADE on a FOREIGN KEY that doesn't reference the PRIMARY KEY
In your third table, Utilizador_POI, you have two FOREIGN KEYs references POI. Unfortunately, the PRIMARY KEY on POI is a composite key, so MySQL has no idea how to handle a DELETE CASCADE, as there is not a one-to-one relationship between the FOREIGN KEY in Utilizador_POI and the PRIMARY KEY of POI.
If you change your tables to all have a PRIMARY KEY of ID, as follows:
CREATE TABLE blah (
id INT(9) AUTO_INCREMENT NOT NULL
....
PRIMARY KEY (id)
);
Then you can reference each table by ID, and both your FOREIGN KEYs and DELETE CASCADEs will work.
I think the problem is that Utilizador_POI.email references POI.email, which itself references Utilizador.email. MySQL is probably upset at the double-linking.
Also, since there seems to be a many-to-many relationship between Utilizador and POI, I think the structure of Utilizador_POI isn't what you really want. Instead, Utilizador_POI should reference a primary key from Utilizador, and a matching primary key from POI.
The problem is in your second table. Your primary key is (email,designacaoPOI), when you try to reference that in your table it gives you error because of this:
InnoDB permits a foreign key to reference any index column or group of
columns. However, in the referenced table, there must be an index
where the referenced columns are listed as the first columns in the
same order.
For it to work, either change the order of your second tale PRIMARY KEY :
CREATE TABLE POI (
email VARCHAR(40) NOT NULL,
designacaoPOI VARCHAR(10) NOT NULL,
coordenadaX INT,
coordenadaY INT,
descricaoPOI VARCHAR(200),
CONSTRAINT pk_POI PRIMARY KEY (designacaoPOI,email), -- changed the order
CONSTRAINT fk_POI FOREIGN KEY (email)
REFERENCES Utilizador(email) ON DELETE CASCADE
);
sqlfiddle demo
or add an index for designacaoPOI:
CREATE TABLE POI (
email VARCHAR(40) NOT NULL,
designacaoPOI VARCHAR(10) NOT NULL,
coordenadaX INT,
coordenadaY INT,
descricaoPOI VARCHAR(200),
CONSTRAINT pk_POI PRIMARY KEY (designacaoPOI,email),
KEY key_designacaoPOI(designacaoPOI), -- added index for that column
CONSTRAINT fk_POI FOREIGN KEY (email)
REFERENCES Utilizador(email) ON DELETE CASCADE
);
sqlfiddle demo
Either of these solutions will let you create your third table without errors.
I am getting an error which I don't understand at all. I am trying to create a table and here is the code:
create table matricula.curso_estudiantes
(codigo varchar(8) NOT NULL,
studentid varchar(8) NOT NULL,
grade varchar(1) NOT NULL,
term numeric(5) NOT NULL,
PRIMARY KEY (codigo, studentid, term),
FOREIGN KEY (codigo)
REFERENCES curso(codigo),
FOREIGN KEY (studentid)
REFERENCES estudiantes(studentid));
insert into matricula.curso_estudiantes values
("COMP2120","X00101010","C",201010),
("COMP2315","X00101010","B",201030),
("COMP2120","X00121111","B",201030),
("COMP2315","X00121111","A",201030),
("COMP2120","X00121234","A",201130),
("COMP2900","X00101010","C",201110),
("COMP3850","X00101010","B",201110),
("COMP2900","X00121111","B",201130),
("COMP3850","X00121111","A",201130),
("COMP2315","X00121234","A",201130),
("COMP2400","X00101010","C",201210),
("MATH1500","X00101010","B",201210),
("COMP2400","X00121111","B",201230),
("MATH1500","X00121111","A",201230),
("COMP3850","X00121234","A",201230),
("MATH1500","X00121234","W",201230);
But I get this error instead:
Error Code:
constraint fails (`matricula`.`curso_estudiantes`, CONSTRAINT
`curso_estudiantes_ibfk_2` FOREIGN KEY (`studentid`) REFERENCES
`estudiantes` (`studentid`))
What seems to be the problem? It creates the table, BUT it gives me that problem and no records are inserted into the table. Which query resolves this? I am new to mySQL so I use a lot of references and examples form the professor.
Do you have the correct corresponding records in the estudiantes table?
A FOREIGN KEY means you need data in the referenced table, or the INSERT won't work.
To fix it, first create and populate your estudiantes and curso tables with valid data.