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
Related
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.
CREATE TABLE Friends_Relations(
buddy_id VARCHAR(255) NOT NULL,
mate_id VARCHAR(255) NOT NULL,
PRIMARY KEY (buddy_id, mate_id),
FOREIGN KEY (buddy_id) REFERENCES Users(id) ON DELETE CASCADE,
FOREIGN KEY (mate_id) REFERENCES Users(id) ON DELETE CASCADE
);
There's this mutual friendship relation where (friend_A, friend_B) is the same as (friend_B, friend_A).
I've tried adding a unique key, but it was to no avail:
ALTER TABLE Friends_Relation ADD UNIQUE KEY (mate_id, buddy_id);
Is there a way to avoid these permutations ?
You can do:
create table friends_relations (
buddy_id varchar(255) not null,
mate_id varchar(255) not null,
constraint uq1 unique (
(least(buddy_id, mate_id)), (greatest(buddy_id, mate_id))
),
primary key (buddy_id, mate_id)
);
Then if it won't accept symmetric rows:
insert into friends_relations (buddy_id, mate_id) values (456, 123);
insert into friends_relations (buddy_id, mate_id) values (123, 456); -- fails
See running example at db<>fiddle.
There's also another trick. What you can alternatively do is to enforce buddy_id < mate_id. This, however, will restrict the way you insert data. For example you can do:
CREATE TABLE Friends_Relations (
buddy_id VARCHAR(255) NOT NULL,
mate_id VARCHAR(255) NOT NULL,
PRIMARY KEY (buddy_id, mate_id),
FOREIGN KEY (buddy_id) REFERENCES Users(id) ON DELETE CASCADE,
FOREIGN KEY (mate_id) REFERENCES Users(id) ON DELETE CASCADE,
constraint ck1 CHECK (buddy_id < mate_id) -- added constraint
);
Then, when you insert:
insert into Friends_Relations (buddy_id, mate_id) values (123, 456); -- succeeds
insert into Friends_Relations (buddy_id, mate_id) values (456, 123); -- fails
from this dba exchange question
ALTER TABLE Friends_Relation ADD UNIQUE KEY
((least(buddy_id,mate_id)), (greatest(buddy_id,mate_id)))
This allows the pair in either order, but still only once.
I am trying to create three tables such as associate, manager and attendance. The attendance table should be having employee and manager details from the other two table which should enable marking the attendance. I created this SQL script. I'm not sure where I am making mistake.
CREATE TABLE associate (
id INT NOT NULL,
idmanager INT NOT NULL,
emp_id DATE NOT NULL,
emp_name VARCHAR(25) NOT NULL,
FOREIGN KEY (id) REFERENCES attendance (associate_id) ON DELETE CASCADE,
FOREIGN KEY (idmanager) REFERENCES attendance (manager_idmanager) ON DELETE CASCADE,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE manager (
id INT NOT NULL,
mgr_usr_id VARCHAR(15) NOT NULL,
mgr_name VARCHAR(25) NOT null,
KEY (id),
KEY (mgr_usr_id),
FOREIGN KEY (id) REFERENCES associate (idmanager) ON DELETE CASCADE,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE attendance (
sno INT NOT NULL,
manager_idmanager INT NOT NULL,
associate_id INT NOT NULL,
date_stamp DATETIME,
state BIT NOT NULL,
PRIMARY KEY (sno)
) ENGINE=INNODB;
Screenshot
It's an issue of ordering. For example, the first statement executed is
CREATE TABLE associate (
which references attendance. However, the attendance table has not yet been created. Switch the order so that any tables that reference other tables come last.
Alternatively, don't put the FOREIGN KEY constraints in the CREATE statements, but them at the end of your script with ALTER TABLE statements. Consider:
CREATE TABLE associate (
id INT NOT NULL,
idmanager INT NOT NULL,
emp_id DATE NOT NULL,
emp_name VARCHAR(25) NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE attendance (
sno INT NOT NULL,
manager_idmanager INT NOT NULL,
associate_id INT NOT NULL,
date_stamp DATETIME,
state BIT NOT NULL,
PRIMARY KEY (sno)
) ENGINE=INNODB;
ALTER TABLE associate ADD FOREIGN KEY (id) REFERENCES associate(id) ON DELETE CASCADE;
Edit
The above is just syntax. To model the requested problem consider orthogonality of information. You might also see/hear "normalization." The basic concept is this: have only one copy of your information. The schema should have a single point of authority for all data. For example, if a user has a birthdate, make sure you don't have an ancillary column that also stores their birthday; it's superfluous information and can lead to data errors.
In this case, what is the relationship? What must come first for the other to exist? Can an attendance be had without a manager? How about a manager without attendance? The former makes no sense. In this case then, I would actually use a third table, to form a hierarchy.
Then, consider that maybe roles change in a company. It would not behoove the DB architect to hard code roles as tables. Consider:
CREATE TABLE employee (
id INTEGER NOT NULL AUTO_INCREMENT,
name VARCHAR(25) NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE role (
id INTEGER NOT NULL AUTO_INCREMENT,
name VARCHAR(30) NOT NULL,
description VARCHAR(254) NOT NULL,
PRIMARY KEY( id ),
UNIQUE( name )
) ENGINE=INNODB;
INSERT INTO role (name, description) VALUES
('associate', 'An associate is a ...'),
('manager', 'A manager follows ...');
CREATE TABLE employee_role (
employee_id INTEGER NOT NULL,
role_id INTEGER NOT NULL,
PRIMARY KEY (employee_id, role_id),
FOREIGN KEY (idemployee_id) REFERENCES employee_id (id) ON DELETE CASCADE,
FOREIGN KEY (role_id) REFERENCES role (id) ON DELETE CASCADE
) ENGINE=INNODB;
CREATE TABLE attendance (
sno INTEGER NOT NULL,
employee_id INTEGER NOT NULL,
date_stamp DATETIME,
state BIT NOT NULL,
PRIMARY KEY (sno),
FOREIGN KEY (idemployee_id) REFERENCES employee_id (id) ON DELETE CASCADE
) ENGINE=INNODB;
From this schema, the attendance needs only one foreign key because everyone is an employee. Employee's can have multiple roles, and they can change. Further, role definitions can change without needing to resort to costly DDL statements (data definition layer changes, like ALTER TABLE), and can be modified with simple DML (data manipulation layer changes, like UPDATE TABLE). The former involves rewriting all entries in the tables, and changing schemas, while the latter involves changing individual entries.
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.
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.