Composite key is blank and constraint fails on inserts - mysql

Having an error when inserting my data into this code into my database. I wanted to make the EventStaff have a primary key made up from StaffID.EventID like in this diagram at the bottom. I can't see to see what I'm doing wrong because the table in StaffID is populated and in TypeID. I was trying to create a composite key of two different tables, is this the wrong way to go about it> i've used the diagram reference.
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`db`.`EventStaff`, CONSTRAINT `fStaff1` FOREIGN KEY (`StaffID`) REFERENCES `Staff` (`StaffID`))
And this is the code for the database
CREATE TABLE EventType (
TypeID INT NOT NULL,
Description VARCHAR(200) NULL,
CONSTRAINT pEventType PRIMARY KEY (TypeID)
);
CREATE TABLE Staff (
StaffID INT NOT NULL,
CONSTRAINT pStaff PRIMARY KEY (StaffID)
);
CREATE TABLE Event (
EventID INT NOT NULL,
Description VARCHAR(500) NULL,
Name VARCHAR(100) NULL,
DateStart DATE NULL,
DateEnd DATE NULL,
TimeStart TIME NULL,
TimeEnd TIME NULL,
TypeID INT NULL,
ClientID INT NULL,
NoBands BOOLEAN NOT NULL,
MaxFoodStall INT NULL,
CONSTRAINT pEvent PRIMARY KEY (EventID),
CONSTRAINT fType1 FOREIGN KEY (TypeID) REFERENCES EventType (TypeID),
);
CREATE TABLE EventStaff (
StaffID int NOT NULL,
EventID int NOT NULL,
Role VARCHAR(45) NULL,
PRIMARY KEY (StaffID, EventID),
CONSTRAINT fStaff1 FOREIGN KEY (StaffID) REFERENCES Staff (StaffID),
CONSTRAINT FEvent1 FOREIGN KEY (EventID) REFERENCES Event (EventID)
);
and here are the inserts
insert into EventType (TypeID, Description) values (1, 'Intuitive attitude-oriented hierarchy');
insert into EventType (TypeID, Description) values (2, 'Mandatory executive concept');
insert into Staff (StaffID) values (1);
insert into Staff (StaffID) values (2);
insert into Event (EventID, Description , DateStart, DateEnd, TimeStart, TimeEnd, NoBands, MaxFoodStall, Name) values (1, 'Cloned 6th generation pricing structure', '2018-03-13', '2018-07-20', '11:18 PM', '4:58 PM', false, 17, 'Swaniawski-Ankunding');
insert into Event (EventID, Description , DateStart, DateEnd, TimeStart, TimeEnd, NoBands, MaxFoodStall, Name) values (2, 'Ameliorated mission-critical throughput', '2017-10-11', '2019-01-05', '10:44 AM', '8:26 PM', true, 4, 'Langworth-Ferry');
insert into EventStaff (Role) values ('Editor');
insert into EventStaff (Role) values ('Budget/Accounting Analyst IV');
https://image.ibb.co/jwaxRx/problem.png

The code you posted to this question has typos, and won't even run as is. Once I fixed those, I was able to reproduce your foreign key error. The problem is actually being caused by these last two inserts:
INSERT INTO EventStaff (Role) VALUES ('Editor');
INSERT INTO EventStaff (Role) VALUES ('Budget/Accounting Analyst IV');
You are not specifying values for the StaffID and EventID, and these columns have been marked as not nullable. They are foreign keys, and it would actually have been OK to insert NULL, had you not marked the columns as non nullable. Here is one way to make this error go away:
INSERT INTO EventStaff (Role, StaffID, EventID)
VALUES ('Editor', 1, 1);
INSERT INTO EventStaff (Role, StaffID, EventID)
VALUES ('Budget/Accounting Analyst IV', 2, 2);
I don't know what values you intend to insert, but the above is one way to go here.
Note that in your insets into the Event table, you don't specify a value for the TypeID column, which is also a foreign key. However, in this case, you have marked the column as nullable, so MySQL accepts it.

Related

Create a categorical column in sql

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

MySQL Error 1452 when adding data to tables

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.

How do i migrate a oracle sql tables to mongodb?

i have created a few tables which have related table using Oracle SQL. My lecturer want me to migrate these into a mongodb , i have searched on web but i am clueless on what they are doing . i know how to setup mongodb and get connection but i dont know how to migrate to mongodb.
This is my tables i have created
CREATE TABLE TBL_EVENT_ORDER
(
ORDER_ID INT CONSTRAINT PK_TBL_EVENT_ORDER
PRIMARY KEY,
CLIENT_ID VARCHAR2(10),
CONSTRAINT FK_CLIENT FOREIGN KEY (CLIENT_ID) REFERENCES
TBL_CLIENT(CLIENT_ID),
ORDER_DATE DATE DEFAULT SYSDATE,
EVENT_ID INT DEFAULT 1,
CONSTRAINT FK_WINE_EVENT FOREIGN KEY (EVENT_ID) REFERENCES
TBL_WINE_EVENT(EVENT_ID)
);
CREATE INDEX IDX_FK_CLIENT_ID_TBL_CLIENT ON TBL_EVENT_ORDER(CLIENT_ID);
INSERT INTO TBL_EVENT_ORDER VALUES
(1,'1',DEFAULT,'1');
INSERT INTO TBL_EVENT_ORDER VALUES
(2,'2',DEFAULT,'1');
INSERT INTO TBL_EVENT_ORDER VALUES
(3,'3',DEFAULT,'1');
INSERT INTO TBL_EVENT_ORDER VALUES
(4,'4',DEFAULT,'1');
CREATE TABLE TBL_WINE
(
WINE_ID INT CONSTRAINT PK_WINE PRIMARY KEY,
WINE_NAME VARCHAR2(20),
PRICE NUMBER(6,2) CONSTRAINT NN_PRICE NOT NULL,
WINE_TYPE VARCHAR2(20) CONSTRAINT NN_WINE_TYPE NOT NULL,
WINE_YEAR INT CONSTRAINT NN_WINE_AGE NOT NULL,
WINE_COUNTRY VARCHAR2(20),
WINE_REGION VARCHAR2(20)
);
INSERT INTO TBL_WINE VALUES
(1,'AGUILA RED',100.50,'BORDEAUX',2010,'COUNTRY1','REGION1');
INSERT INTO TBL_WINE VALUES
(2,'CLOUD BAY',150,'BORDEAUX',2010,'COUNTRY2','REGION2');
INSERT INTO TBL_WINE VALUES
(3,'HARLAN ESTATE',175.50,'BORDEAUX',2010,'COUNTRY3','REGION3');
INSERT INTO TBL_WINE VALUES
(4,'KRUG',200,'BORDEAUX',2010,'COUNTRY4','REGION4');
CREATE TABLE TBL_ORDER_DETAIL
(
ORDER_ID INT,
WINE_ID INT,
CONSTRAINT PK_ORDER_DETAIL PRIMARY KEY (ORDER_ID, WINE_ID),
CONSTRAINT FK_EVENT_ORDER FOREIGN KEY (ORDER_ID) REFERENCES
TBL_EVENT_ORDER(ORDER_ID),
ORDER_QTY INT CONSTRAINT NN_ORDER_QTY NOT NULL,
UNIT_PRICE NUMBER(6,2),
EXCLUSIVE_IMPORT CHAR(1)
);
CREATE INDEX IDX_FK_ORDER_ID_EVENT_ORDER ON TBL_ORDER_DETAIL(ORDER_ID);
CREATE INDEX IDX_FK_WINE_ID_WINE ON TBL_ORDER_DETAIL(WINE_ID);
INSERT INTO TBL_ORDER_DETAIL VALUES
(1,1,3,100.50,'N');
INSERT INTO TBL_ORDER_DETAIL VALUES
(2,2,1,150,'N');
INSERT INTO TBL_ORDER_DETAIL VALUES
(3,3,4,175.50,'N');
INSERT INTO TBL_ORDER_DETAIL VALUES
(4,4,2,200,'Y');

Allow a foreign key insertion only if another foreign key is matched

I have these 3 tables:
--company--
company_id (primary key)
name
--location--
location_id (primary key)
company_id (foreign key referencing company.company_id)
name
--asset--
asset_id (primary_key)
company_id (foreign key referencing company.company_id)
location_id (foreign key referencing location.location_id)
name
I would like to enforce this: a location_id for an asset is acceptable only if asset.company_id = location.company_id
currently I'm enforcing this through the application, I was wondering if it's possible to do this using only MySQL.
drop table company;
create table company
( company_id int not null auto_increment,
name varchar(100) not null,
primary key(company_id)
)ENGINE=InnoDB
;
insert into company(name) values ('acme widgets');
insert into company(name) values ('goober chocolates');
insert into company(name) values ('Fat R Us');
drop table location;
create table location
( location_id int not null,
company_id int not null,
name varchar(100) not null,
primary key(company_id,location_id),
FOREIGN KEY (company_id ) REFERENCES company(company_id)
)ENGINE=InnoDB
;
insert into location(location_id,company_id,name) values (1,1,'Cambridge MA');
insert into location(location_id,company_id,name) values (1,2,'Boston MA');
insert into location(location_id,company_id,name) values (1,3,'Topeka KS');
insert into location(location_id,company_id,name) values (2,1,'Everywhere USA');
insert into location(location_id,company_id,name) values (2,666,'Fail Test this will fail');
create table asset
( asset_id int not null auto_increment,
company_id int not null,
location_id int not null,
name varchar(100) not null,
primary key(asset_id),
CONSTRAINT fk_asset_cl FOREIGN KEY (company_id,location_id)
REFERENCES location(company_id,location_id)
)ENGINE=InnoDB
;
insert into asset(company_id,location_id,name) values (1,1,'typewriter');
insert into asset(company_id,location_id,name) values (1,8,'typewriter fail');
remember that your FK must be back to a single parent table with a key in the same composite order (company,location) in this example
insert into asset(company_id,location_id,name) values (1,8,'typewriter fail');
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails ...

How do I make a column under customer that references "id" from the employer table

CREATE TABLE College (
CollegeID INTEGER AUTO_INCREMENT NOT NULL,
Collegename varchar(50),
PRIMARY KEY(CollegeID));
INSERT INTO `College` (`CollegeID`, `Collegename`) VALUES
(1, 'Harvard'),
(2, 'Princeton'),
(3, 'Columbia'),
(4, 'Georgetown'),
(5, 'Yale');
CREATE TABLE Customer (
CustomerID INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
FirstName varchar(20),
LastName varchar(20),
DateHired DATE,
CollegeID INTEGER REFERENCES College(CollegeID));
INSERT INTO `Customer` (`CustomerID`, `FirstName`, `LastName`, `DateHired`, `CollegeID`) VALUES
(111, 'Johnny', 'Silvia', '20100301', 1),
(222, 'Billy', 'Blank', '20070111', 2),
(333, 'Susan', 'Anderson', '20021222', 3),
(444, 'Samantha', 'Love', '19990521', 3),
(555, 'Bill', 'Gray', '20010913', 5);
CREATE TABLE `employer` (
`id` INTEGER NOT NULL,
`EmployerName` varchar(60) NOT NULL,
PRIMARY KEY(id));
INSERT INTO `employer` (`id`, `EmployerName`) VALUES
(1111, 'McDonalds');
If a customer can have one but only one employer, then yes, add the employer id reference into your customer table.
If a customer can have more than one employer, then you have to create another table that contains Ids of customers and Ids of employers.
CREATE TABLE Customer (
CustomerID INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
EmployerID INTEGER REFERENCES employer(id),
FirstName varchar(20),
LastName varchar(20),
DateHired DATE,
CollegeID INTEGER REFERENCES College(CollegeID));
I don't know mysql well, I just took the syntax you used, but if you want to create foreign key references check this link out http://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.html
You are talking about FOREIGN KEYs
To create FOREIGN KEYs on your table/s:
/* Create the Parent Table */
CREATE TABLE College (
ID INTEGER AUTO_INCREMENT NOT NULL,
CollegeName VARCHAR(50),
PRIMARY KEY(ID)
);
/* Create the Child Table and Referece the Column CollegeId of this table to the Id Column of College Table */
CREATE TABLE Customer (
ID INT(11) AUTO_INCREMENT NOT NULL,
Name VARCHAR(40),
CollegeID INT(11),
PRIMARY KEY(ID),
CONSTRAINT FK_Customer_College FOREIGN KEY (CollegeID) REFERENCES College (ID)
);
Follow this syntax:
CONSTRAINT ForeignKeyName FOREIGN KEY (ColumnName) REFERENCES TableName (ColumnName)
On the other hand, if you have already created the tables, you can just create the FOREIGN KEY by altering the table:
ALTER ChildTable ADD CONSTRAINT ForeignKeyName FOREIGN KEY (ChildColumn) REFERENCES ParentTable (ParentColumn);